为什么我的jquery .on('change')不适用于动态添加的选择 [英] Why is my jquery .on('change') not working for dynamically added selects

查看:462
本文介绍了为什么我的jquery .on('change')不适用于动态添加的选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在动态添加选择元素,就像下面的HTML一样.我不确定为什么.on('change'...)对动态选择不起作用.我想念什么?

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?

我正在使用Chrome 24.0.1312.57 + jQuery 1.8.3

I'm using 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>

推荐答案

您的代码:

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

将事件处理程序附加到#x元素中的select.

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'); });

这会将事件处理程序附加到#y元素,该事件处理程序将委派给其子级选择"元素

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

来自 http://api.jquery.com/on/

.on()方法将事件处理程序附加到jQuery对象中当前选择的元素集.

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

这篇关于为什么我的jquery .on('change')不适用于动态添加的选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆