我正在动态添加select元素,如下面的HTML所示。我不确定为什么.on('change‘...)不适用于动态选择。我遗漏了什么?
我使用的是Chrome 24.0.1312.57 + jquery 1.8.3。
<script type="text/javascript">
  $(document).ready(function() {
      $('#x select').on('change', function () { alert('helo'); })
      $('#y select').on('change', function () { alert('helo'); })
      $('#x').html($('#y').html());
  });
</script>
<div id="x"></div>
<div id="y">
    <select>
        <option>O1</option>
        <option>O2</option>
    </select>
</div>发布于 2013-02-19 01:41:30
你的代码:
$('#x select').on('change', function () { alert('helo'); })将事件处理程序附加到#x元素内的select。
你想要的东西(根据我的理解)是这样的:
$("#y").on('change','select',function () { alert('helo'); });这会将一个事件处理程序附加到委托给其子“select”元素的#y元素
来自http://api.jquery.com/on/
.on()方法将事件处理程序附加到jQuery对象中当前选定的元素集。
发布于 2013-02-19 01:38:42
在初始页面加载时,对不在DOM中的元素的事件绑定将不起作用。您需要绑定到DOM中更靠上的元素,以允许事件向下渗透。这通常是我采取的方法:
$(document).on({
  change: function() {
    alert('helo');
  }
}, '#x select');
$(document).on({
  change: function() {
    alert('helo');
  }
}, '#y select');我更喜欢它,因为你可以很容易地添加后续事件。
$(document).on({
  change: function() {
    alert('helo');
  },
  blur: function() {
    alert('helo');
  }
}, '#x select');发布于 2017-03-14 14:48:08
不过,不要使用.live()/.bind()/.delegate(),。您应该使用.on()。
对于静态和动态选择更改
$(document).on('change', 'select', function (e) {
    // do something 
});https://stackoverflow.com/questions/14942048
复制相似问题