虽然这个问题以前已经回答过很多次了,但我想我将为未来的用户提供一个更完整和可靠的答案。主要的答案确实解决了问题,但是我相信了解一些不同的显示/隐藏东西的方法可能会更好。
.
使用css()改变显示
我以前就是这么做的直到我发现了其他的方法。
Javascript:
$("#element_to_hide").css("display", "none"); // To hide
$("#element_to_hide").css("display", ""); // To unhide
优点:
隐藏和取消。差不多就是这样。
缺点:
如果将"display"属性用于其他用途,则必须硬编码隐藏之前的值。所以如果你有"inline",你必须做$("#element_to_hid").css("display", "inline");否则它将默认返回“block”或其他它将被迫进入的状态。
容易出现错别字。
例如:https://jsfiddle.net/4chd6e5r/1/
.
使用addClass()/removeClass()改变显示
在建立这个例子的时候,我实际上遇到了这个方法的一些缺陷,使得它非常非常不可靠。
Css / Javascript:
.hidden {display:none}
$("#element_to_hide").addClass("hidden"); // To hide
$("#element_to_hide").removeClass("hidden"); // To unhide
优点:
有时它隐藏了…。参考示例中的p1。
在取消隐藏后,它有时会返回到使用以前的显示值....。参考示例中的p1。
如果你想获取所有隐藏对象,你只需要执行$(".hidden")。
缺点:
如果直接在html上设置显示值,则不隐藏。参考例子中的p2。
如果使用css()在javascript中设置显示,则不隐藏。请参见样例中的p3。
代码稍微多一点,因为你必须定义一个css属性。
例如:https://jsfiddle.net/476oha8t/8/
.
使用toggle()改变显示
Javascript:
$("element_to_hide").toggle(); // To hide and to unhide
优点:
总是工作。
允许您不必担心切换之前是哪个状态。它的明显用途是....切换按钮。
简短而简单。
缺点:
If you need to know which state it is switching to in order to do something not directly related, you will have to add more code (an if statement) to find out which state it is in.
Similar to the previous con, if you want to run a set of instructions that contains the toggle() for the purpose of hiding, but you don't know if it is already hidden, you have to add a check (an if statement) to find out first and if it is already hidden, then skip. Refer to p1 of the example.
Related to the previous 2 cons, using toggle() for something that is specifically hiding or specifically showing, can be confusing to others reading your code as they do not know which way they will toggle.
例如:https://jsfiddle.net/cxcawkyk/1/
.
使用hide()/show()改变显示
Javascript:
$("#element_to_hide").hide(); // To hide
$("#element_to_hide").show(); // To show
优点:
总是工作。
在取消隐藏后,它将返回到使用之前的显示值。
你总是知道你要切换到哪个状态,所以你:
如果状态很重要,在更改状态之前不需要添加if语句来检查可见性。
如果状态很重要,就不会让读代码的人弄不清楚你要切换到哪个状态。
直观。
缺点:
如果要模拟切换,必须先检查状态,然后切换到另一个状态。使用toggle()来代替这些。参考示例中的p2。
例如:https://jsfiddle.net/k0ukhmfL/
.
总的来说,我认为最好是hide()/show(),除非你特别需要它是一个切换。我希望这些信息对你有帮助。