Update
(2013 年 8 月)看起来 jQuery 发生了变化,只需调用hide
可能不再是最快的选择(尽管为了简洁和清晰起见,它可能仍然是更好的选择)。看看这个更新的基准测试用例 http://jsperf.com/check-element-viz-before-hide/3.
First, it should be noted that the runtime effect of this will be infinitesimal, and you would be hard-pressed to create a situation in which this would be the bottle-neck in your performance.
然而,第二种方法可能会更快,因为它已经具备了if
无论如何检查内置的:
// ... line 7996 (jQuery 1.8.1):
if (!values[index] && display !== "none") {
jQuery._data(elem, "olddisplay", display);
}
// ...
换句话说,该函数仅在 DOM 元素上执行(如果它还没有)display: none
。仍有可能.is()
方法设法更快一点,因为它避免了更少的方法调用,但看看方法本身将很快消除这些恐惧:
// ...line 6804:
return !!selector && (
typeof selector === "string" ?
// If this is a positional/relative selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
rneedsContext.test(selector) ?
jQuery(selector, this.context).index(this[0]) >= 0 :
jQuery.filter(selector, this).length > 0 :
this.filter(selector).length > 0);
// ...
简而言之,第二个更快——jsPerf 测试用例 http://jsperf.com/check-element-viz-before-hide.