简体   繁体   English

为什么 jQuery on change 事件会多次触发?

[英]Why does jQuery on change event fire multiple times?

I am trying to bind event handlers to dynamically added <select> elements.我正在尝试将事件处理程序绑定到动态添加的<select>元素。 But the event is firing 1 extra time for each time the select list changes.但是,每次 select 列表更改时,该事件都会触发 1 次额外时间。 (First time it fires once, then twice, then three times, etc.) (第一次它会触发一次,然后是两次,然后是三次,等等)

 $(document).on('change', '.gender-select', function() { $('.gender-select').change(function() { alert($(this).find("option:selected").text()); }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <select class="gender-select"> <option value="">- Select Gender -</option> <option value="m">Male</option> <option value="f">Female</option> </select>

https://jsfiddle.net/L3p9ez5d/3/ https://jsfiddle.net/L3p9ez5d/3/

Solution解决方案

Thanks, Rory McCrossan, for your answer.谢谢,罗里麦克罗桑,你的回答。 Quite simple, I had a static event handler inside of a delegated one, so handlers kept getting added when the delegated handler fired.很简单,我在委托的事件处理程序中有一个 static 事件处理程序,因此当委托处理程序触发时,处理程序会不断添加。

The reason is because you are nesting your event handlers.原因是因为您正在嵌套事件处理程序。 You've placed a static event handler within a delegated one, so each time an event happens another handler is added.您已将 static 事件处理程序放置在委托的事件处理程序中,因此每次发生事件时都会添加另一个处理程序。 This is also the reason why nothing happens when you first select an option.这也是为什么当你第一次选择 select 时什么都没有发生的原因。

To fix the problem simply remove the inner static event handler:要解决此问题,只需删除内部 static 事件处理程序:

 $(document).on('change', '.gender-select', function() { console.log($(this).find("option:selected").text()); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <select class="gender-select"> <option value="">- Select Gender -</option> <option value="m">Male</option> <option value="f">Female</option> </select>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM