jQuery 不会在页面加载时附加克隆 [英] jQuery wont append a clone on page load

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

问题描述

如果您单击选项 2,它会从页面加载中附加原始克隆,但不会在每次单击按钮时重复.

1.将元素变为红色...</a><br/><a href="#" class="copy">2.附加原始黑色元素...</a><br/><br/><div id="容器"><div class="element">这是一个元素!</div>

$(document).ready(function () {var obj = $(".element").clone(true);$(".copy").click(function (e) {e.preventDefault();//警报(对象);//只是看看它是否还存在.$("#container").append(obj);});$(".modify").click(function (e) {e.preventDefault();$(".element").css("颜色", "#F00");});});

这是我的 CodePen 链接 http://codepen.io/anon/pen/dsvLm

有什么想法吗?

解决方案

单个 DOM 元素的一个特性,您可能不知道,就是它只能有一个父元素.这是有道理的,因为 DOM 树将元素向上、向下和横向连接起来,并且只有一个父元素链接(以及一个 next 和一个 prev 同级元素链接),但有多个子元素的列表.

当你克隆一个元素时,你创建了一个新的 DOM 元素,它实际上是 DOM 树中的一个新分支(如果只是一个小分支).调用 append 将元素添加到其新父元素,但它还会将克隆的父链接指向其新父元素.通过一遍又一遍地附加相同的元素,您只需更改单个元素的父元素(即在 DOM 树中移动它).

相反,每次需要时,只需为断开连接的克隆对象(在其原始状态)创建一个新克隆:

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

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

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?

解决方案

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

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

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