问题描述
当我们只能在j Query中使用hide()
时,为什么必须从文档对象模型中选择remove()
或detach()
个元素?
Why do we have to remove()
or detach()
elements from Document Object Model when we can just hide()
in j Query?
推荐答案
您不必不必删除或分离.但是您可以.我的意思是,这取决于情况.
Well you don't have to remove or detach. But you can. What I mean is that it depends on the situation.
何时使用hide
:
隐藏只是简单地应用内嵌样式display: none
.如果您要暂时隐藏某些东西然后再显示它,则隐藏起来既快捷又有用.
hiding is simply applying an inline style of display: none
. Hiding is fast and useful if you want to temporarily hide something and then show it.
何时使用remove
:
在调用remove()
时,实际上是从DOM中删除了元素.元素及其所有数据和事件侦听器.如果您已经完成了元素并且不再需要它,这将很有用.隐藏它只会在您的DOM中留下垃圾.
when you call remove()
you physically remove the element(s) from the DOM. The elements, along with all their data and event listeners. This is useful if you are done with the element and you won't be needing it again. Hiding it would just leave garbage in your DOM.
何时使用detach
:
分离与去除非常相似,但是分离元素时,将保留其数据和事件侦听器.如果要将元素从DOM中的一个位置移动到另一个位置,这将很有用.
detaching is very similar to removing but when you detach an element you keep its data and event listeners. This is useful if you want to move and element from one place in the DOM to another.
这篇关于为什么要使用remove()或detach()而不是hide()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!