我正在动态添加选择元素,如下面的HTML.我不确定为什么.on(‘更改’…)不能用于动态选择.我错过了什么?
我正在使用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.
你想要的东西(从我理解的东西)是这样的:
$("#y").on('change','select',function () { alert('helo'); });
这会将事件处理程序附加到#y元素,该元素将委托给其子元素的“select”元素
从http://api.jquery.com/on/起
The .on() method attaches event handlers to the currently selected set of elements in the jQuery object.