简体   繁体   中英

Jquery repeater, why .keyup and .change does not triggered on the second items and beyond?

The .keyup and .change only triggered in the first input but not after I added a new item. Is there a way the .keyup and .change triggered when adding new field?

http://jsfiddle.net/q8pcoaxf/

$('.field').on('change keyup',function() {
    alert('alert');
})

A jQuery selector only selects those elements present in the DOM at the time of its execution. In older versions of jQuery, there was once a function .live() that would also bind to any elements of the given selector added at a later point in time, but it has since been removed.

What you can do is bind to the document via .on() with an additional selector as the second argument. But keep in mind that this will fire on every trigger of the bound events and check against the selector, so for performance reasons, if you can narrow down the elements that will be added to a specific parent (like a form probably in your case), you should definitely do that instead of binding to the document.

On a sidenote: Binding to change and keyup will result in the callback function to be executed twice in this example case, because the alert window popping up will result in the input losing focus and therefore the change event being triggered as well.

 // will bind on the document and be executed for all change and keyup events on any element that has the class "field" $(document).on('change keyup', '.field', function() { alert('alert'); }); // let's say you had a form with the id #dynamic_inputs where the inputs are added to, // this would be the preferable way to handle it: //$('#dynamic_inputs').on('change keyup', '.field', function() { // alert('alert'); //}); function addNewInput() { var newInput = document.createElement('input'); newInput.classList.add('field'); document.body.appendChild(newInput); } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button onclick="addNewInput()">add new input</button><br> <input class="field" /> 

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