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

前端 未结 10 559
既然无缘
既然无缘 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:36

    Your code:

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

    attaches an event handler to the select inside the #x element.

    What you want (from what i understood) is something in the lines of:

    $("#y").on('change','select',function () { alert('helo'); });
    

    This attaches an event handler to the #y element that gets delegated to its children 'select' elements

    From http://api.jquery.com/on/

    The .on() method attaches event handlers to the currently selected set of elements in the jQuery object.

提交回复
热议问题