Jquery empty() remove() detach() 方法的区别





引言:
最近项目中用到了这几个方法,感觉很大程度上有些相似,查了Jquery的api,同时也找了很多博客文章,发现还是理解不到区别。最后在很多材料和自己的事例验证中,终于找到了区别,不敢独占特拿出来分享。

 


方法简介:

 empty()
This method removes not only child (and other descendant) elements, but also any text within the set of matched elements. This is because, according to the DOM specification, any string of text within an element is considered a child node of that element.
该方法不仅删除它的子节点,同时也删除该节点的文本域(根据DOM规范,节点的文本域也被认为是子节点)。

 

 remove( [selector] )
selectorA selector expression that filters the set of matched elements to be removed.

Similar to .empty(), the .remove() method takes elements out of the DOM. Use.remove() when you want to remove the element itself, as well as everything inside it. In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed. To remove the elements without removing data and events, use.detach() instead.
和empty方法类似,remove方法也是从DOM里删除元素。当你想要删除节点本身和节点里的所有东西的时候,可以使用remove方法。除了节点本身以外,节点绑定的事件 和该节点相关的JQuery数据,也会被同时清除。当需要清除节点本身,但是不需要清除绑定的事件和数据的时候,可以使用detach方法。


 detach( [selector] )
selectorA selector expression that filters the set of matched elements to be removed.

The .detach() method is the same as .remove(), except that .detach() keeps all jQuery data associated with the removed elements. This method is useful when removed elements are to be reinserted into the DOM at a later time.
detach方法和remove方法很相似,但是它会保留所有JQuery相关的数据和绑定的事件。当你删除之后,想要在后来的某个时候重新加入时,这个方法将会很有用。


猜你喜欢

转载自blog.csdn.net/u013299635/article/details/79608324
今日推荐