jQuery - 如何只进行一次自定义事件触发?

时间:2011-03-06 02:05:50

标签: javascript jquery

我需要控制触发事件的顺序。为确保我的自定义事件仅在另一个事件完成后触发,我将在第一个事件的处理程序中触发自定义事件。

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

自定义事件绑定:

$(document).ready(function() {
     $(".HwRadioButton").bind("onAnswerChange",function(event) {
    //custom event stuff

    });

});

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

谢谢!

3 个答案:

答案 0 :(得分:5)

在您的代码中尝试:

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

将触发单击的一个元素上的onAnswerChange。

答案 1 :(得分:2)

您应该使用one之类的

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

答案 2 :(得分:1)

对于该选择器选择的所有项,

$(".HwRadioButton").trigger("onAnswerChange")会触发onAnswerChange。仅针对$(this).trigger("onAnswerChange")触发事件。