简体   繁体   中英

Why does jQuery on change event fire multiple times?

I am trying to bind event handlers to dynamically added <select> elements. But the event is firing 1 extra time for each time the select list changes. (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/

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.

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. This is also the reason why nothing happens when you first select an option.

To fix the problem simply remove the inner static event handler:

 $(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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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