动态添加内容的奇怪行为
Strange behavior with dynamically added content
这是我的小插件: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
不止一次,但如果我在添加新按钮后没有调用它,那么它将不适用于新按钮。
我哪里做错了?
问题是因为当您创建一个新的 button
时,您正在 所有 .myalert
元素上实例化您的插件的另一个实例。相反,只需在新按钮上实例化它,如下所示:
$('.add-more').click(function() {
var uniq = new Date().valueOf();
$('<button class="myalert" data-id="' + uniq + '">show alert</button>').appendTo('body').my_alert();
});
解决您的问题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();
});
});
这是我的小插件: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
不止一次,但如果我在添加新按钮后没有调用它,那么它将不适用于新按钮。
我哪里做错了?
问题是因为当您创建一个新的 button
时,您正在 所有 .myalert
元素上实例化您的插件的另一个实例。相反,只需在新按钮上实例化它,如下所示:
$('.add-more').click(function() {
var uniq = new Date().valueOf();
$('<button class="myalert" data-id="' + uniq + '">show alert</button>').appendTo('body').my_alert();
});
解决您的问题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();
});
});