问题描述
我在这样的复选框上附加了onchange
事件:
I'm attaching an onchange
event on checkboxes like this:
$("input[type='checkbox'][name='auswahl[]']").on("change", function() {
alert($(this).attr("id") + ' ' + $("label[for='" + $(this).attr("id") + "']").text() + $(this).attr("checked"));
});
复选框如下所示:
<input type="checkbox" name="auswahl[]" id="aus_nunatsiaqnews_ca"><label for="aus_nunatsiaqnews_ca" title="Canada">Nunatsiaq News</label>
不幸的是,该事件触发了两次.当我隔离上面给出的代码并将其放在测试页上时,一切都很好,并且该事件仅触发一次.需要帮助.
Unfortunately the event is firing twice. When I isolate the code given above and put it on a test page everything is fine and the event is firing only once.Need help.
推荐答案
通常,当具有"onClick"事件的控件嵌套在具有"onClick"事件的另一个控件中时,通常会发生这种情况.单击一个元素会触发两个元素的事件,因为无法知道您要单击哪个元素.幸运的是,在Javascript中可以避免这种情况.在HTML中,将"$ event"参数传递给处理click事件的函数,如下所示:
This usually happens when a control with an "onClick" event is nested inside another control with an "onClick" event. Clicking one of the elements triggers the events for both elements since there is no way of knowing which of them you wanted to click.fortunately, this can be prevented in Javascript. in the HTML, pass the "$event" parameter to the function that handles the click event like so:
onClick="myFunc($event)"
然后在"myFunc"中使用"stopPropagation",如下所示:
and then, in "myFunc" use "stopPropagation" as such:
myFunc($event) {
// ... some code ... //
$event.stopPropagation();
}
这篇关于复选框onchange触发两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!