jQuery - How do I make custom event fire only once?
I need to control the order in which events are fired. 开发者_Python百科To ensure that my custom event is fired only after another event has finished I am triggering the custom event in the handler of the first event.
$(".HwRadioButton").click(function(event) {
//Stuff that needs to happen before custom event
...
//trigger custom event
$(".HwRadioButton").trigger("onAnswerChange");
});
Custom event binding:
$(document).ready(function() {
$(".HwRadioButton").bind("onAnswerChange",function(event) {
//custom event stuff
});
});
The problem is that I have 12 elements that have a class attribute value of ".HwRadioButton". The event, "onAnswerChange" is triggered 12 times. Why is that? Should I even need to select any elements? I just want to define a custom event and explicitly trigger it.
Thanks!
In your code try:
$(".HwRadioButton").click(function(event) {
//Stuff that needs to happen before custom event
...
//trigger custom event
$(this).trigger("onAnswerChange");
});
that will trigger the onAnswerChange on the one element that was clicked.
You should use one like
$('.HwRadioButton').one('click', function() {
alert('This will be displayed only once.');
});
$(".HwRadioButton").trigger("onAnswerChange")
triggers onAnswerChange
for all items selected by that selector. Trigger the event only for $(this).trigger("onAnswerChange")
.
精彩评论