天天看点

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

$(".tags .btn_confirm").click(function(){
         var text = $(this).text();
          //添加的a元素
         var node  = $("<a href='#' class='test btn_confirm'>"+text+ "<span class='remove'>X</span></a>");
         if($(".tags_selected").children().length >= 8){
                 $(".selector").show();
         }else{
             $(".selector").hide();
             $(".tags_selected").append(node);
         }
         
     })
       //这里使用on(),方法,console.log()没有打印任何东西,也没有报错
     $(".remove").on("click",function(e){
         console.log(e);
         //$(this).prev().remove();
         $(this).parent().remove();
     })
           

第一种解决方法:使用live,原因是jquery的事件绑定在页面加载时就已经完成,所以之后动态添加的class将无法绑上事件,

所以使用live可以解决这个问题。不过live只支持jquery1.9以前(大概),之后版本的就可以使用委托事件

$(".remove").live("click",function(){
  
});
           

第二种解决方法:采用事件委托或代理方式绑定

$(document).on("click", ".remove", function(e){
     console.log(e);
     $(this).parent().remove()
 });
           

委托事件高级写法:

function $domOfSth(text){
        return $("<a href='#' class='test btn_confirm'>"+text+ "<span class='remove'>X</span></a>").on('click','.remove',function(){
            console.log('xxxx');
        });
    }
    
    $('#xxx').append($domOfSth('xxx'));
           

这样的优势在于:

  • 在$domOfSth函数里面,这个dom可以绑定事件的写法相当灵活
  • 对于事件一目了然,可维护性好
  • 事件绝对牢牢绑定在插入dom上,不会因为js读到

    $(".tags_closebtn")

    这一句的时候,页面找不到这个对象的尴尬。。。

    这个尴尬刚好是你点击事件未绑定到插入的dom上的原因。因为,js读到

    $(".tags_closebtn").on('click')

    的时候,浏览器还没更新html代码呢,然后jq就跑去找,发现tm页面上根本没有这个类,是假的,是化学的成分。。。
jq