克隆的div随着原始div的改变而改变

时间:2012-11-06 10:00:36

标签: jquery css clone

我有一个div“maindiv”。这里面还有div,包括“imagediv”。在jQuery中,我写道:

$(document).ready(function() {

    ......

    var copydiv = $('#maindiv').clone();
    var number = 1;
    $("body").delegate("#imagediv", "mousedown", function(event) {

        $("#maindiv").attr('id', "changedmain" + number);
        $("#imagediv").attr('id', "changedimage" + number);
        copydiv.insertAfter("#appendafter");
        number = number + 1;
    });
});​

HTML:

<div id="appendafter"></div>
<div id="maindiv">
.
.
.
</div>

对于此代码,首次附加copydiv后,添加的克隆的id为“maindiv”,所有内部div都具有正确的。但是当number为2时,克隆包含“changemain2”而不是maindiv.WHY是这个?任何补救措施????

3 个答案:

答案 0 :(得分:4)

首先,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
});

Demo

答案 1 :(得分:1)

问题在于您的变量编号,必须在

之外声明

答案 2 :(得分:1)

Alrighty ........好吧,亲爱的函数clone()基本上维护了一个引用。 我只是放置了声明

var copydiv = $('#maindiv').clone();

在委托声明中:

  $("body").delegate("#imagediv", "mousedown", function(event) {

它现在如何工作......没有想法...但是在紧迫的期限内......你永远不会想太多...... Njoi!

相关问题