[英]jQuery - How do I make custom event fire only once?
我需要控制事件触发的顺序。 为了确保仅在另一个事件完成后才触发我的自定义事件,我在第一个事件的处理程序中触发该自定义事件。
$(".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次。 这是为什么? 我是否还需要选择任何元素? 我只想定义一个自定义事件并显式触发它。
谢谢!
在您的代码中尝试:
$(".HwRadioButton").click(function(event) {
//Stuff that needs to happen before custom event
...
//trigger custom event
$(this).trigger("onAnswerChange");
});
这将触发被单击的一个元素上的onAnswerChange。
您应该使用一个像
$('.HwRadioButton').one('click', function() {
alert('This will be displayed only once.');
});
$(".HwRadioButton").trigger("onAnswerChange")
触发该选择器选择的所有项目的onAnswerChange
。 仅针对$(this).trigger("onAnswerChange")
触发事件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.