jQuery wont append a clone on page load

爷,独闯天下 提交于 2019-12-11 10:05:15

问题


If you click option 2, it appends the original clone from page load but it wont repeat every time the button is clicked.

<a href="#" class="modify">1. Turn the element red...</a><br />
<a href="#" class="copy">2. Append the original black element...</a><br /><br />
<div id="container">
    <div class="element">This is an element!</div>
</div>
$(document).ready(function () {
    var obj = $(".element").clone(true);
    $(".copy").click(function (e) {
        e.preventDefault();
        //alert(obj); //Just to see if it still exists.
        $("#container").append(obj);
    });
    $(".modify").click(function (e) {
        e.preventDefault();
        $(".element").css("color", "#F00");
    });
});

Here is my CodePen link http://codepen.io/anon/pen/dsvLm

Any ideas?


回答1:


One feature of an individual DOM element, that you may not have been aware of, is that it can only have one parent. This makes sense as the DOM tree connects elements up, down, and sideways to each other and only have a single parent-element link (and a single next and single prev sibling element link) but a list of multiple children.

When you clone an element, you create a new DOM element that is effectively a new branch in a DOM tree (if only a small one). Calling append adds the element to its new parent, but it also points a parent link of your clone to its new parent. By appending the same element over and over you are simply changing the parent of a single element (i.e. moving it in the DOM tree).

Instead just make a new clone of your disconnected cloned object (in its original state) each time you need one:

JSFiddle: http://jsfiddle.net/TrueBlueAussie/7h8MK/2/

$("#container").append(obj.clone(true));



回答2:


You need to create the clone while appending.Use:

var obj = $(".element");
$(".copy").click(function (e) {
    e.preventDefault();
    //alert(obj); //Just to see if it still exists.
    $("#container").append(obj.clone(true));
});

Demo



来源:https://stackoverflow.com/questions/22174241/jquery-wont-append-a-clone-on-page-load

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!