这是我的小插件: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
上老项目超过一次,但如果我不添加一个新的按钮后调用它,那么它将在新的按钮不起作用。
我在哪里做错了什么?
解决您的问题提琴
$(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();
});
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句