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'); });
});