jQuery 绑定点击
我有以下情况:
在 html 页面中,我有一个动态生成的按钮,类似于:
<div id='myButton'></div>
此 html 页面包含一个脚本(例如 A.js),它处理网站的大部分功能,在此脚本中按钮被绑定到一个处理程序:
$("#myButton").bind("click", function(){
foo();
});
到目前为止很简单。现在,仅在特定情况下,我需要相同的按钮来执行第二个功能。这必须通过另一个脚本来完成,该脚本动态生成并注入到 html 站点内。因此,html 看起来与此类似:
<script type=text/javascript src=A.js></script>
<script type=text/javascript>
//Dynamically generated script
</script>
我不想覆盖以前的函数,我仍然需要执行该函数,但我也需要在第一个函数之前执行该函数。并且脚本包含在网站上的方式无法更改。
所以,我写了以下内容(在第二个脚本标签内):
$("#myButton").bind("click",
function(){
bar(); // I still want foo() to be executed but after this is executed first.
});
是否可以做这样的事情?请注意,我无法控制脚本如何包含在我的网站上。改变该顺序是不可能的。
I have the following situation:
In a html page i have a dynamically generated button, similar to:
<div id='myButton'></div>
This html page includes a script (e.g., A.js), that handles most of the functionality of the site, and in this script the button is being bound to an handler:
$("#myButton").bind("click", function(){
foo();
});
So far its simple. Now, only in a particular situation, i need the same button to execute a second function. This has to be done through another script, dynamically generated and injected inside the html site. So the html will look similar to this:
<script type=text/javascript src=A.js></script>
<script type=text/javascript>
//Dynamically generated script
</script>
I do not want to override the previous function, i still need that to be executed, but also i need this function to be executed before the first one. And the way scripts are included on the site cannot be changed.
So, I have written the following (inside the second script tag):
$("#myButton").bind("click",
function(){
bar(); // I still want foo() to be executed but after this is executed first.
});
Is it possible to do something like this? Note that i do not have control on how scripts are included on my site. Altering that order is not possible.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您仍然可以对同一事件有更多绑定
他们将按照第一个的顺序被解雇代码
,这样你就可以拥有:
并且在其他脚本中,
它就会起作用
只要将它们放在
$(document).ready( function() {}); 下,
You can still have more bindings to the same event
they will be fired sorted by what was the first in the code
so you can have:
and in other script
this will act as
as long as you place them under
$(document).ready( function() {});
为什么不将 Bolt foo,bar 组合到该函数中..
或者您可以将 foo() 实现为回调函数。
why not just combine bolt foo,bar into that function..
or you may implement the foo() as callback function.