jQuery on()方法绑定动态元素的点击事件无响应的解决办法

(编辑:jimmy 日期: 2024/10/3 浏览:2)

$('#check_all').on('click' , function(){
alert(1);
});
$("#yujinlist").append(html);
count++; 
} 

以上代码执行时,点击#check_all时,alert一直没反应,后在网上查资料时,才知道on前面的元素也必须在页面加载的时候就存在于dom里面, 那原话是这样的:

支持给动态元素和属性绑定事件的是live和on,其中live在JQUERY 1.7之后就不推荐使用了。现在主要用on,使用on的时候也要注意,on前面的元素也必须在页面加载的时候就存在于dom里面。动态的元素或者样式等,可以放在on的第二个参数里面。

因为我先输出相关html,再执行就没问题了。

<div class="row"><div class="col-xs-12"><div class="control-group"><label class="control-label bolder blue">选择镇街</label><div class="row"><div class="checkbox col-xs-1"><label><input type="checkbox" class="checkbox" id="check_all" /><span class="lbl">全区</span></label></div><div id="check_item"><div class="checkbox col-xs-1 "><label><input name="towm'+count+'" type="checkbox" class="checkbox" /><span class="lbl">西南街道</span></label></div><div class="checkbox col-xs-1 "><label><input name="towm'+count+'" type="checkbox" class="checkbox" /><span class="lbl">云东海街道</span></label></div><div class="checkbox col-xs-1"><label><input name="towm'+count+'" type="checkbox" class="checkbox" /><span class="lbl">白坭镇</span></label></div><div class="checkbox col-xs-1"><label class="block"><input name="towm'+count+'" type="checkbox" class="checkbox" /><span class="lbl">乐平镇</span></label></div><div class="checkbox col-xs-1"><label class="block"><input name="towm'+count+'" type="checkbox" class="checkbox" /><span class="lbl">大塘镇</span></label></div><div class="checkbox col-xs-1"><label class="block"><input name="towm'+count+'" type="checkbox" class="checkbox" /><span class="lbl">芦苞镇</span></label></div><div class="checkbox col-xs-1"><label class="block"><input name="towm'+count+'" type="checkbox" class="checkbox" /><span class="lbl">南山镇</span></label></div></div></div></div></div></div><hr />'; 
$('#check_all').on('click' , function(){
var that = this;
$('#check_item').find('input:checkbox')
.each(function(){
alert(2);
this.checked = that.checked;
$(this).closest('.col-xs-1').toggleClass('selected');
});
});

下面看下jquery on() 方法绑定动态元素

jQuery on()方法是官方推荐的绑定事件的一个方法。使用 on() 方法可以给将来动态创建的动态元素绑定指定的事件,例如append等。

<div id="test">
<div class="evt">evt1</div>
</div>

错误的用法,下面方法只为第一个class 为 evt 的div 绑定了click事件,使用append动态创建的div则没有绑定

<script>
// 先绑定事件再添加div
$('#test .evt').on('click', function() {alert($(this).text())});
$('#test').append('<div class="evt">evt2</div>');
</script>

正确的用法如下:

<script>
$('body').on('click', '#test .evt', function() {alert($(this).text())});
$('#test').append('<div class="evt">evt2</div>');
</script>

以上所述是小编给大家介绍的jQuery on()方法绑定动态元素的点击事件无响应的解决办法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!

一句话新闻

高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。