Javascript jQuery - 将事件处理程序附加到预先存在的点击事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5183529/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery - Append an event handler to preexisting click event
提问by Nick
I have a click event that is defined already. I was wondering what the best way would be to append another event handler to this event without touching this code (if possible).
我有一个已经定义的点击事件。我想知道在不触及此代码的情况下将另一个事件处理程序附加到此事件的最佳方法是什么(如果可能)。
Is there a way to just append another event handler to the already defined click event?
有没有办法将另一个事件处理程序附加到已经定义的点击事件?
This is the current click event definition:
这是当前的点击事件定义:
$(".HwYesButton", "#HwQuizQuestions")
.append("<a href='javascript:void(0);' rel='.HwYesButton'>Yes</a>")
.click(function(event) {
var button = $(this).parent();
var questionId = button.attr('id');
$iadp.decisionPoint["HwQuizYourself"].Input.inputProvided(questionId);
button.find(".HwNoButton").removeClass("HwButtonSelected");
$(this).addClass("HwButtonSelected");
button.removeClass("HwQuestionSkipped");
$iadp.flat.setBoolean(questionId, true);
return false;
});
回答by Felix Kling
The only thing you can do is to attach another (additional) handler:
您唯一可以做的就是附加另一个(附加)处理程序:
$(".HwYesButton", "#HwQuizQuestions").click(function() {
// something else
});
jQuery will call the handlers in the order in which they have been attached to the element.
jQuery 将按照它们附加到元素的顺序调用处理程序。
You cannot "extend" the already defined handler.
您不能“扩展”已经定义的处理程序。
Btw. your formulation is a bit imprecise. You are not defining a click event. You are only attaching click event handlers. The click event is generated by the browser when the user clicks on some element.
顺便提一句。你的公式有点不准确。您没有定义点击事件。您只是附加点击事件处理程序。当用户单击某个元素时,浏览器会生成 click 事件。
You can have as many click handlers as you want for one element. Maybe you are used to this in plain JavaScript:
对于一个元素,您可以拥有任意数量的点击处理程序。也许你已经习惯了纯 JavaScript:
element.onclick = function() {}
With this method you can indeed only attach one handler. But JavaScript provides some advanced event handling methodswhich I assume jQuery makes use of.
使用这种方法,您确实只能附加一个处理程序。但是JavaScript 提供了一些我认为 jQuery 使用的高级事件处理方法。
回答by jessieloo
I know this is an old post, but perhaps this can still help someone since I still managed to stumble across this question during my search...
我知道这是一个旧帖子,但也许这仍然可以帮助某人,因为我在搜索过程中仍然设法偶然发现了这个问题......
I am trying to do same kind of thing except I want my action to trigger BEFORE the existing inline onClick events. This is what I've done so far and it seems to be working ok after my initial tests. It probably won't handle events that aren't inline, such as those bound by other javascipt.
我正在尝试做同样的事情,除了我希望我的操作在现有的内联 onClick 事件之前触发。这是我到目前为止所做的,在我的初步测试后它似乎工作正常。它可能不会处理非内联事件,例如由其他 javascipt 绑定的事件。
$(function() {
$("[onClick]").each(function(){
var x = $(this).attr("onClick");
$(this).removeAttr("onClick").unbind("click");
$(this).click(function(e){
// do what you want here...
eval(x); // do original action here...
});
});
});
回答by Jishnu A P
You can just write another click event to the same and the both will get triggered. See it here
您可以将另一个点击事件写入相同的内容,两者都会被触发。看这里
<a id="clickme">clickme</a>
<script>
$('#clickme').click(function () {
alert('first click handler triggered');
});
$('#clickme').click(function () {
alert('second click handler triggered');
});
</script>
回答by chim
Ajax can complicate the issue here. If you call two events the first being an ajax call, then the second event will probably fire well before the response comes back.
Ajax 可能会使问题复杂化。如果您调用两个事件,第一个是 ajax 调用,那么第二个事件可能会在响应返回之前触发。
So even though the events are being fired in the correct order, what you really need is to get in to the callback function in the ajax call.
因此,即使事件以正确的顺序被触发,您真正需要的是进入 ajax 调用中的回调函数。
It's difficult to do without editing the original code.
不编辑原始代码是很难做到的。
回答by Volomike
Yes you can. Let's say that I have a tag cloud, and clicking a tag will remove the tag by default. Something like:
是的你可以。假设我有一个标签云,默认情况下单击一个标签将删除该标签。就像是:
<div class="tags">
<div class="tag">Tag 1</div>
<div class="tag">Tag 2</div>
</div>
<script>
$(document).ready(function(){
$('.tag').click(function(e){
e.preventDefault();
$(this).fadeOut('slow',function(){
$(this).remove();
});
return false;
});
});
</script>
Now let's say that's bundled into an included library for a project, but you want to provide a developer-friendly way to intercept those click events and prompt the user an AYS (Are You Sure?) dialog. In your mind you might be thinking something like:
现在假设它已捆绑到项目的包含库中,但您希望提供一种对开发人员友好的方式来拦截这些点击事件并提示用户 AYS(你确定吗?)对话框。在您的脑海中,您可能会想这样的事情:
<script>
$(document).ready(function(){
$('.tag').beforeRemove(function(){
if (AYS() === false) {
return false; // don't allow the removal
}
return true; // allow the removal
});
});
</script>
The solution, therefore, would be:
因此,解决方案是:
<div class="tags">
<div class="tag">Tag 1</div>
<div class="tag">Tag 2</div>
</div>
<script><!-- included library script -->
$(document).ready(function(){
$.fn.beforeRemove = $.fn.click;
$('BODY').on('click','.tag',function(e){
e.preventDefault();
console.log('debug: called standard click event');
$(this).fadeOut('slow',function(){
$(this).remove();
});
return false;
});
});
</script>
<script><!-- included in your page, after the library is loaded -->
$(document).ready(function(){
$('.tag').beforeRemove(function(){
var sWhich = $(this).text();
console.log('debug: before remove - ' + sWhich);
return false; // simulate AYS response was no
// change return false to true to simulate AYS response was yes
});
});
</script>
In this example, the trick is that we extended jQuery with a beforeRemove
trigger that is a duplicate of the click
trigger. Next, by making the library utilize the $('BODY').on('click','.tag',function(e){...});
handler, we made it delay and call afterour page's beforeRemove
trigger fired. Therefore, we could return false
in beforeRemove
if we got a negative AYS condition and therefore not allow the click
event to continue.
在这个例子中,诀窍是我们使用beforeRemove
触发器的副本扩展了 jQuery click
。接下来,通过让库利用$('BODY').on('click','.tag',function(e){...});
处理程序,我们使它延迟并在页面beforeRemove
触发器触发后调用。因此,如果我们得到负的 AYS 条件,我们可以返回false
,beforeRemove
因此不允许click
事件继续。
So, run the above and you'll see that clicks on the tags won't remove the item. Now, switch the beforeRemove
function to return true
(as if you had a positive response to an AYS prompt), and the click
event is allowed to continue. You have appended an event handler to a preexisting click
event.
所以,运行上面的,你会看到点击标签不会删除项目。现在,将beforeRemove
函数切换为返回true
(就像您对 AYS 提示有肯定响应一样),并且click
允许事件继续。您已将事件处理程序附加到预先存在的click
事件。