使用hide、prop、attr或css隐藏JQuery元素之间的区别

Difference between using hide, prop, attr or css to hide an element with JQuery

本文关键字:元素 JQuery 之间 区别 隐藏 css hide prop attr 使用      更新时间:2023-09-26

我设置了4个div来测试使用的不同结果

$("#div1").hide();
$("#div2").prop("hidden", true);
$("#div3").css("display","none");
$("#div4").attr("hidden", true);

我可以看到结果是(我使用的是1.11.3版本):

<div id="div1" style="display: none;">Something</div>
<div id="div2" hidden="">Something</div>
<div id="div3" style="display: none;">Something</div>
<div id="div4" hidden="hidden">Something</div>

有四种不同的方法可以达到几乎相同的结果,这对我来说似乎有点困惑。我在.hide()或display中看到了一些解释:没有?jQuery,但我想知道是否有人能提供更多信息,主要是,我什么时候应该使用哪个??

//this is a wrapper function.  simply adds display none inline.  for ease of use
$("#div1").hide();
//prop is used to manipulate any property on the object.  hidden is a property.  so it doesn't stop you from doing it.
$("#div2").prop("hidden", true);
//css is a wrapper for the style attribute.  display is a valid css property so it won't stop it
$("#div3").css("display","none");
//this one seems odd.  i thought it would be hidden="hidden"  but anyway.  attr() is used to change the attributes on the markup.  hidden is a valid attribute so it doesn't stop you
$("#div4").attr("hidden", true);

这一切都与你的编码风格有关。如果它们都有效,你就可以使用你最喜欢的一个。如果可能的话,尽量保持一致,imho。

当然有区别,但我不会全部介绍。

真实的生活故事:

我刚刚有一个项目,其中我需要根据DOM元素的显示属性来过滤它们。相同的DOM元素通过使用.hide()设置为"none",并通过设置.show()显示

这种用法虽然简洁明了,但在按显示属性进行筛选时遇到了问题,因为它在控制台输出中总是显示"none"。即使元素列表显示"块"。因此,使用.hide()进行缓存

你不只是想用你最喜欢的东西。只有当你最喜欢适合你特定需求的东西时;)