简体   繁体   中英

.change() function on dom element generated after load

i'm trying to catch a change() on a select which is added after the dom generation but i can't success. Here is a sample code:

HTML:

<div class="test" id="divTest"></div>

jQuery:

$('#divTest').click(function(){ $(this).parent().append("<select id='testSel'><option value='f'>F</option><option value='F'>D</option></select>");});

$('#testSel').change(function(){
    alert('change');
});

I want to see the alert when i change the value in the select..

And here is a fiddle. http://jsfiddle.net/T8J8p/3/

Two problems:

  1. Your select element's ID is #testS not #testSel . 1
  2. You need to use event delegation for this, through jQuery's on() method:
$('body').on('change', '#testS', function(){
    alert('change');
});

JSFiddle demo .

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.


1. This related to original JSFiddle featured in the question (available here ). The question has since been edited.

You need event delegation dynamically added DOM::

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

$(document).on('change','#testS',function(){
 alert('change');
});

Demo

Try this,

$('body').on("change", "#testSel", function(){
    alert('change');
})

You have to bind event using event delegation as the element is added to the DOM after the DOM loaded:

$(document).on('change','#testSel',function(){
    alert('change');
});

See Details HERE

$('#divTest').click(function(){
  $(this).parent().append("<select id='testS'><option value='f'>F</option><option value='F'>D</option></select>");
  $('#testS').change(function(){alert('change');});
});

You can't bid to something that does not exist yet, so bind it after the click, inside the function. And there was a typo in the selector #testS vs #testSel

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