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

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

    Event binding to elements that are not in the DOM on initial page load will not work. You need to bind to an element further up the DOM that exists to allow the event to trickle down. This is usually the approach that I take:

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

    I prefer it as you can add subsequent events easily.

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

提交回复
热议问题