Why is my jquery .on('change') not working for dynamically added selects

前端 未结 10 561
既然无缘
既然无缘 2020-12-31 01:12

I\'m adding select elements dynamically, like in the below HTML. I\'m not sure why the .on(\'change\' ...) is not working for the dynamic select. What am I missing?

<
10条回答
  •  一个人的身影
    2020-12-31 01:52

    The whole point of .on() is so that you can bind the event to something other than the document. This is what the now depreciated .live() did and it is inefficient in most cases. You are ment to bind the event to the closest parent element that will not be dynamically changed.

    As far as I am aware this is the correct syntax:

    $('#x').on('change', 'select', function(){
        alert('hello');
    });
    

    If #x or #y will be changed, wrap them on an element and bind the event to that.

提交回复
热议问题