使用jquery1.10版本,动态在一个div.里面增加a元素,包含有span子元素。我要在span子元素上添加一个click事件,点击span元素删除整个a元素,但是试了很多方法都不行,直接用clik ,不行,用on()方法也不行。
$(".tags .btn_confirm").click(function(){
var text = $(this).text();
//添加的a元素
var node = $("<a href='#' class='tseleced btn_confirm'>"+text+ "<span class='tags_closebtn'>X</span></a>");
if($(".tags_selected").children().length >= 8){
$(".selector_warn").show();
}else{
$(".selector_warn").hide();
$(".tags_selected").append(node);
}
})
//这里使用on(),方法,console.log()没有打印任何东西
$(".tags_closebtn").on("click",function(e){
console.log(e);
$(this).prev().remove()
})
使用live
$("button").live("click",function(){
});
原因是jquery的事件绑定在页面加载时就已经完成,所以之后动态添加的class将无法绑上事件,所以使用live可以解决这个问题。不过live只支持jquery1.9以前(大概),之后版本的就可以使用
$('body').on("click", ".tags_closebtn", function () {
});
$(this).prev().remove()
为什么不是
$(this).parent().remove()
动态的dom不能绑定上事件,就让它冒泡给父级。用事件委托的方式。
on的委托事件写法。
$(document).on("click", ".tags_closebtn", function(e){
console.log(e);
$(this).prev().remove()
});
$(this).closest('a').remove()
很明显用错了。既然是动态添加的元素,那么绑定就不能直接on("click",function(){})
,可以采用事件委托或代理方式绑定,如
$("body").on("click",".tags_closebtn",function(){});
霍霍,既然有人提出了事件委托,那么对于这种动态添加的事件,我建议这么写:
function $domOfSth(text){
return $("<a href='#' class='tseleced btn_confirm'>"+text+ "<span class='tags_closebtn'>X</span></a>").on('click','.tags_closebtn',function(){
console.log('xxxx');
});
}
$('#xxx').append($domOfSth('xxx'));
这样的优势在于:
在$domOfSth函数里面,这个dom可以绑定事件的写法相当灵活
对于事件一目了然,可维护性好
事件绝对牢牢绑定在插入dom上,不会因为js读到
$(".tags_closebtn")
这一句的时候,页面找不到这个对象的尴尬。。。
这个尴尬刚好是你点击事件未绑定到插入的dom上的原因。因为,js读到$(".tags_closebtn").on('click')
的时候,浏览器还没更新html代码呢,然后jq就跑去找,发现tm页面上根本没有这个类,是假的,是化学的成分。。。