gpt4 book ai didi

jquery - 为什么我的 jquery .on ('change' ) 不适用于动态添加的选择

转载 作者:行者123 更新时间:2023-12-03 21:52:49 25 4
gpt4 key购买 nike

我动态添加选择元素,如下面的 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>

最佳答案

您的代码:

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

将事件处理程序附加到 #x 元素内的选择。

你想要的(根据我的理解)是这样的:

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

这会将事件处理程序附加到 #y 元素,该元素被委托(delegate)给其子“select”元素

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

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

关于jquery - 为什么我的 jquery .on ('change' ) 不适用于动态添加的选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14942048/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com