首先,Id 在 DOM 中必须是唯一的。在这种情况下,如果您要附加多个集合,请切换到类选择器。
接下来,您的变量number
是本地的并重新定义并重置为1
每个mousedown
var copydiv = $('.maindiv').clone();
var number = 1; // This was redefined and set as 1 on every `mousedown`
// So make it global
$("body").delegate(".imagediv","mousedown",function(event){
$(".maindiv").attr('class',"changedmain" + number);
$(".imagediv").attr('class',"changedimage" + number );
copydiv.insertAfter("#appendafter"); // You might have to change this too
// depending if this is repeated too
number = number+1;
}
此外,最好使用.on()
函数进行委托
$("body").on("mousedown", ".imagediv", function(event){
$(".maindiv").attr('class',"changedmain" + number);
$(".imagediv").attr('class',"changedimage" + number );
copydiv.insertAfter("#appendafter"); // You might have to change this too
// depending if this is repeated too
number = number+1;
}
解决方案:
问题在于使用的方法。使用克隆的元素.clone()
将保存引用,因此它不会添加新元素,而是会不断更新以前引用的对象。
这是解决方案:
var number = 1; //Our Counter Script
function createDiv() {
//Lets create a new div,
// I mean WHY CLONE AT the first place??
// We are delegating events anyway :p
$("<div />", {
html : $('#maindiv').html(), // add the HTML of div we are trying to keep
// ^ Better used cached
// version is not updated regularly
id : "maindiv-"+number // add the generate id number
}).insertAfter("#appendafter"); // Now insert it
number++;
}
$("body").on("mousedown", ".imagediv", function(event){
createDiv(); //Delegating on all elements with `imagediv` class
});