问题描述:
我在html页面中根据$.getJSON获取到的data动态的往页面中加入checkbox,并设定了checkbox的click事件,一开始的源代码如下所示:
$.getJSON("/ebook_template_category",
{acid:chacid},
function(data){
$.each(data, function(i, item){
htmlcont += '<input type="checkbox" name="acidcate" chacid='+chacid+' value='+item.etcid+' />'+item.name;
});
if(data)
{
htmlcont +='<li><input type="checkbox" id="check-all" />全选';
htmlcont += '<span> </span><button id="commitcate">确定</button></li>';
}
htmlcont += '</ul>';
var divshow=$("#category-check").text('');
divshow.append(htmlcont);
});
代码中蓝色部分为我要在页面中动态添加的checkbox元素,之后我对该元素的click事件进行绑定,使用了如下错误的方法:
$("#check-all").click(function(){
$("input[name='acidcate']").attr("checked",this.checked);
});
$("input[name='acidcate']").click(function(){
$("#check-all").attr("checked", $("input[name='acidcate']").length==$("input[name='acidcate']:checked").length? true:false);
});
即我用了一般的绑定事件方法,其结果为点击“全选”等checkbox元素,不促发相应的click事件,经google得知,动态添加到页面中的元素需用.live进行绑定,即将绑定事件代码做如何更改即可:
$("#check-all").live("click", function(){
$("input[name='acidcate']").attr("checked",this.checked);
});
$("input[name='acidcate']").live("click", function(){
$("#check-all").attr("checked", $("input[name='acidcate']").length==$("input[name='acidcate']:checked").length? true:false);
});
详细原因请参见链接:
http://beinet.cn/Default.aspx?id=beacd37f-2ac5-49a6-8cd9-a15b0d2f9a3f
http://blog.163.com/quan2006@126/blog/static/17022863520114421019458/