gpt4 book ai didi

javascript - 如何创建元素的浅拷贝?

转载 作者:行者123 更新时间:2023-12-03 06:11:23 25 4
gpt4 key购买 nike

最近在this question我问如何查明类里面是否存在风格。 (skobaljic)告诉我我需要克隆元素。在元素(jQuery 方法)的调用 .clone() 期间,生成的对象包含默认样式(例如来自样式表),因此插入的样式不包含在克隆中。我是这样理解的。但是,当我需要检测是否存在 6 种样式时,克隆完整元素(包括可能有数百或数千个子元素)似乎很奇怪。我检查了 jQuery 的克隆方法代码。有这样的:

destElements = getAll( clone );
srcElements = getAll( elem );

因此函数 getAll 被调用了两次。

然后我检查了包含 getAll 的内容:

var ret = typeof context.getElementsByTagName !== "undefined" ?
context.getElementsByTagName( tag || "*" ) :
typeof context.querySelectorAll !== "undefined" ?
context.querySelectorAll( tag || "*" ) :
[];

来自 Mozilla 手册:

The Element.getElementsByTagName() method returns a live HTMLCollection of elements with the given tag name. The subtree underneath the specified element is searched, excluding the element itself.

Document.querySelectorAll() - Returns a list of the elements within the document (using depth-first pre-order traversal of the document's nodes) that match the specified group of selectors. The object returned is a NodeList.

因此,很明显,创建元素的深拷贝是没有意义的,而且需要性能。当我需要进行深入搜索/比较时,这个问题会更加严重,这会导致资源的过度浪费。我想克隆没有子元素的元素。这可能吗?克隆应该包含默认样式,就像使用 .clone() 所做的那样。怎么做?

最佳答案

我相信这可以帮助你:

来源:http://www.w3schools.com/jsref/met_node_clonenode.asp

  // Copy the element and its child nodes
var clone_with_child = yourElement.cloneNode(true);
// Copy only the element
var clone_without_child = yourElement.cloneNode(false);

关于javascript - 如何创建元素的浅拷贝?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39299654/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com