我正在尝试创建一个隐藏页面上所有可见元素的jQuery脚本,
然后在有人点击按钮后,再次显示隐藏的所有元素。
我知道我可以在每个分隔符上使用.is(':visible')
选择器并存储可见的分隔符,然后在所有这些分区上使用.hide();
。最后,我知道当有人点击我的按钮时,我可以再次使用.show();
。
但我想知道是否有更好的方法来做到这一点。
我想在一次扫描中隐藏所有元素不会是一个大问题(可能类似$(document).hide()
会这样做吗?)
但最重要的是,我如何以一种很好的方式存储所有隐藏的元素,以便我可以再次恢复它们?
答案 0 :(得分:7)
在隐藏元素之前,将一个类应用于所有元素,以便稍后识别它们:
// hide everything visible, except the button clicked
$('button#hideVisible').click(function() {
$(':visible').each(function() {
$(this).addClass("unhideable");
$(this).hide();
});
$(this).show();
});
或者,在这种特定情况下,您实际上不需要使用jQuery each
。您可以通过将:visible
选择器与jQuery not selector相结合来简化jQuery功能,以使用this
值排除按钮:
// much simpler version of applying an unhideable class and hiding visible elements
$('button#hideVisible').click(function() {
$(':visible').not(this).addClass("unhideable");
$(':visible').not(this).hide();
});
<强>更新强>
然而,虽然上述两种解决方案非常适用于您不需要用户干预来取消隐藏元素的情况,例如自动脚本,但上述两个示例的问题是它们隐藏了父元素的主要元素。按钮,这意味着该按钮将被隐藏,尽管它不是明确的。如果您需要用户再次单击该按钮以取消隐藏元素,则上述两种解决方案是有限的。
因此,此功能的下一个发展是确保我们使用jQuery's parentsUntil方法排除父母:
$('button#hideVisible').click(function() {
// if we're in the hide state, unhide elements and return
if( $('button').hasClass('ancestors') == true ) {
$(this).html("Hide");
$('.unhideable').show();
$('.unhideable, .ancestors').removeClass("unhideable").removeClass("ancestors");
return;
}
// hide all children of the button. While this might not make sense for a button
// it's helpful to use this on clickable DIV's that may have descendants!
$('#hideVisible').find(':visible').addClass("unhideable");
$('#hideVisible').find(':visible').hide();
// put a class on button ancestors so we can exclude them from the hide actions
$('#hideVisible').parentsUntil("html").addClass("ancestors");
$('html').parentsUntil("html").addClass("ancestors");
// let's not forget to include the button as well
$(this).addClass("ancestors");
// make sure all other elements on the page that are not ancestors and
// not descendants of button end up marked as unhideable too!
$(':visible').not('.ancestors').addClass("unhideable");
// nice debug output to give you an idea of what's going on under the hood
// when the hide operation is finally called
$(':visible').not('.ancestors, html').each(function() {
console.info($(this).get());
});
// hide the remaining elements on the page that aren't ancestors,
// and include the html element in the exception list as for some reason,
// we can't add class attributes to it
$(':visible').not('.ancestors, html').hide();
// change the button text to "Show"
$(this).html("Show");
});
取消隐藏所有无法隐藏的元素:
接下来,当您想取消隐藏它们时,只需致电:
$('.unhideable').show();
最后,如果需要,您可以通过致电:
自行清理$('.unhideable, .ancestors').removeClass("unhideable").removeClass("ancestors");
<强>样本:强>
有关此功能的演示,请参阅此jsfiddle。
答案 1 :(得分:0)
试试这个:
$('div:visible').hide();
$('div:hidden').show();