Welcome 微信登录

首页 / 脚本样式 / JavaScript / jQuery on()方法绑定动态元素的点击事件无响应的解决办法

$("#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()方法绑定动态元素的点击事件无响应的解决办法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!