动态生成的下拉列表不会触发 jquery 更改事件 [英] jquery change event does not fire for dynamic generated dropdown
问题描述
我通过按钮点击事件生成一个下拉框.在此下拉菜单中 onchange 事件不会触发.谁能帮助我为什么会这样?代码如下
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script><script type="text/javascript">jQuery(document).ready(function($) {$('#pin').click(function() {var content='<select class="pincode"><option value="1">1</option><option value="2">2</option></select>';$("#test").append(content);});$(".pincode").change(function(){警报($(this).val());});});<style type="text/css">div {填充:35px;向左飘浮;}}</风格><title>新的网络项目</title>头部><身体><h1>使用 jQuery 的动态下拉</h1><div><select class="pincode"><option value="1">1</option><option value="2">2</option></选择>
<div id="测试"></div><input type="button" id="pin" value="pin"/>
您需要使用委托,因为该元素是动态加载的,并且在创建事件侦听器时并不存在.
$(document).on('change',".pincode", function(){警报(这个.值);});
请注意,您的样式标签中有一个额外的 }
.最好在 CSS 文件中包含此内容.
演示 这里
查看有关 .on() 的链接.在委托事件的第一部分可以阅读:
<块引用>事件处理器只绑定到当前选中的元素;在您的代码调用事件处理程序"时,它们必须存在于页面上.
i generate one dropdown box through button click event. In this dropdown onchange event does not fire. Can anyone help me why this is heapped? code is below
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
jQuery(document).ready(function($) {
$('#pin').click(function() {
var content='<select class="pincode"><option value="1">1</option><option value="2">2</option></select>';
$("#test").append(content);
});
$(".pincode").change(function(){
alert($(this).val());
});
});
</script>
<style type="text/css">
div {
padding: 35px;
float: left;
}
}
</style>
<title>New Web Project</title>
</head>
<body>
<h1>Dynamic Drop Down using jQuery</h1>
<div>
<select class="pincode">
<option value="1">1</option>
<option value="2">2</option>
</select>
</div>
<div id="test"></div>
<input type="button" id="pin" value="pin" />
You need to use delegation because the element is loaded dynamically and was not there when the event listener was created.
$(document).on('change',".pincode", function(){
alert(this.value);
});
Please notice you have one extra }
inside your style tags. Would be better to have this in the CSS file.
Demo here
Check this link about .on(). In the delegated events part one can read:
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to 'the event handler'.
这篇关于动态生成的下拉列表不会触发 jquery 更改事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!