2011-03-06 138 views
1

我需要控制事件被触发的顺序。为了确保我的自定义事件仅在另一个事件完成后触发,我正在触发第一个事件处理程序中的自定义事件。jQuery - 如何让自定义事件只触发一次?

$(".HwRadioButton").click(function(event) {  
     //Stuff that needs to happen before custom event 
     ... 
    //trigger custom event    
     $(".HwRadioButton").trigger("onAnswerChange"); 
}); 

定制事件绑定:

​​

的问题是,我有有 “.HwRadioButton” 的一类属性值12组的元素。事件“onAnswerChange”被触发12次。这是为什么?我是否还需要选择任何元素?我只想定义一个自定义事件并明确触发它。

谢谢!

回答

5

在您的代码尝试:

$(".HwRadioButton").click(function(event) {  
     //Stuff that needs to happen before custom event 
     ... 
    //trigger custom event    
     $(this).trigger("onAnswerChange"); 
}); 

将触发被点击的一个元素的onAnswerChange。

+0

完美。现在有意义.. – Nick 2011-03-06 02:12:59

+1

不客气。 – 2011-03-06 02:38:34

1

$(".HwRadioButton").trigger("onAnswerChange") triggers onAnswerChange对于该选择器所选择的所有项目。仅针对$(this).trigger("onAnswerChange")触发事件。

2

您应该使用one

$('.HwRadioButton').one('click', function() { 
    alert('This will be displayed only once.'); 
}); 
+0

为什么这个投票被拒绝? – Kimtho6 2011-03-06 02:15:52