动态添加内容的奇怪行为

时间:2016-02-13 12:48:42

标签: javascript jquery jquery-plugins

这是我的小插件:jsfiddle

$(function() {
    $.fn.my_alert = function() {
        this.each(function() {
            $(this).bind("click", function(e) {
                alert($(this).attr('data-id'));
            });
        });
    }
});

$(document).ready(function() {
    $('.myalert').my_alert();

    $('.add-more').click(function() {
        var uniq = new Date().valueOf();
        var newHtml = "<button class='myalert' data-id='" + uniq + "' >show alert</button>";
        $('body').append(newHtml);
        $('.myalert').my_alert();
    });
});

如果我在添加新按钮后调用插件,那么alert旧项目上的id不止一次,但如果我在添加新按钮后没有调用它,那么它就不会处理新按钮。

我在哪里做错了什么?

2 个答案:

答案 0 :(得分:0)

问题在于,当您创建新的button时,您将在所有 .myalert元素上实例化插件的另一个实例。相反,只需在新按钮上实例化它,如下所示:

$('.add-more').click(function() {
    var uniq = new Date().valueOf();
    $('<button class="myalert" data-id="' + uniq + '">show alert</button>').appendTo('body').my_alert();
});

Updated fiddle

答案 1 :(得分:0)

修复您的问题fiddle

$(function(){
$.fn.my_alert = function(){
   this.each(function() {  
            $( this ).bind("click",function(e){ 
               alert($( this ).attr('data-id'));
             });
        });
    } 
 });


$(document).ready(function(){
   $('.myalert').my_alert();
   $('.add-more').click(function() {
     var uniq =  new Date().valueOf();
      var newHtml = $("<button class='myalert' data-id='"+uniq+"' >show alert</button>");
    $('body').append(newHtml);
    newHtml.my_alert();
    });
});
相关问题