首页 > jq动态添加的元素使用on()无法绑定click事件

jq动态添加的元素使用on()无法绑定click事件

使用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'));

这样的优势在于:

【热门文章】
【热门文章】