.clone()和.html()有什么区别? [英] What's the difference between .clone() and .html()?

查看:245
本文介绍了.clone()和.html()有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Jquery的.clone()和.html()函数有什么区别?

What is the difference between Jquery's .clone() and .html() functions?

jquery文档状态:

Jquery documentation states:

.clone()方法对匹配项进行深层复制 元素,这意味着它会复制匹配的元素以及所有 他们的后代元素和文本节点.

The .clone() method performs a deep copy of the set of matched elements, meaning that it copies the matched elements as well as all of their descendant elements and text nodes.

在HTML文档中,.html()可用于获取任何内容 元素.如果选择器表达式匹配多个元素, 只有第一个匹配项才会返回其HTML内容.

In an HTML document, .html() can be used to get the contents of any element. If the selector expression matches more than one element, only the first match will have its HTML content returned.

在我看来,这些似乎是可以互换的,那么在特定情况下,一个会被另一个使用吗?

To me these seem to interchangeable, so are there specific situation where one would be used of the other?

推荐答案

.clone()返回jQuery对象,而.html()返回字符串.

.clone() returns a jQuery object while .html() returns a string.

如果要复制jQuery对象,请使用.clone(),并使用.html()以字符串格式获取jQuery对象的内部HTML.每种方法都有自己的用途(和成本).

Use .clone() if you want a copy of the jQuery objects and use .html() to get the inner HTML of a jQuery object in a string format. Each method has its own purpose (and cost).

此外,正如 sgroves 指出的那样,".clone()对元素的集执行深层复制由选择器找到,而.html()仅[使用] 第一个匹配的元素." *

Also, as sgroves pointed out, ".clone() performs a deep copy of the set of elements found by the selector, while .html() only [uses] the first matched element."*

*尽管请注意,.html(newContent)将设置匹配元素的 的内部HTML. 小提琴

*Although note that .html(newContent) will set the inner HTML of a set of matched elements. Fiddle

另一个注意:(通常)更快"选项是在执行DOM操作时使用字符串而不是jQuery对象(

Another note: the (generally) "faster" option is to use strings rather than jQuery objects when doing DOM manipulation (JSPerf). Thus, I'd recommend .html() if all you need is text content. Again though: each method has its own purpose.

这篇关于.clone()和.html()有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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