jQuery的追加不会载入网页克隆 [英] jQuery wont append a clone on page load

查看:121
本文介绍了jQuery的追加不会载入网页克隆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您单击选项2,它从附加页面加载原始克隆,但它不会重复每次按钮被点击的时间。

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");
    });
});

下面是我的codePEN链接 HTTP://$c$cpen.io/匿名/笔/ dsvLm

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

任何想法?

推荐答案

个人DOM元素的一个特点,那你可能没有意识到的是,的只能有一个父的。这是有道理的DOM树连接的元素向上,向下,并侧身,彼此只能有一个父元素链接(和单个下一单$ P $光伏同级元素链接),但多个孩子的名单。

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.

当您克隆一个元素,创建一个新的DOM元素实际上是在DOM树新分支(如果只有一个小)。主叫追加添加元素到其新的父,但它也指出的克隆到其新的父的父链接。通过反复你只是改变单一元素的父附加同一元素(即,在DOM树中移动它)。

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).

而不是只让你断开克隆对象的新的clone(在其原始状态),每次需要时间:

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

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

这篇关于jQuery的追加不会载入网页克隆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆