在隐藏元素之前,对所有元素应用一个类,以便以后识别它们:
// hide everything visible, except the button clicked
$('button#hideVisible').click(function() {
$(':visible').each(function() {
$(this).addClass("unhideable");
$(this).hide();
});
$(this).show();
});
each
或者,在这种特定情况下,您实际上并不需要使用 jQuery 。您可以通过将:visible
选择器与jQuery not 选择器组合使用以下值来排除按钮来简化 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 的 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。