中级 jQuery
2009-08-29 00:00:00 来源:WEB开发网技巧 #3 - 缓存选择器
最后一个性能技巧利用了几乎所有 jQuery 选择器都返回 jQuery 对象这个特性。这意味着在理想的情况下,您仅需要运行选择器一次,并且能够轻松地将所有函数连接在一起,或缓存结果供以后使用。您也不要担心缓存,因为与总体可用内存相比,返回的对象是很小的。
清单 3 给出了一些关于如何利用缓存的例子。
清单 3. 缓存
// Imagine a function that hides all the div's with a class of "hideable"
// when a button is pressed. These DIV's might reappear later when
// working with the page, so the button can be pressed any number of
// times, and the DIV's that have reappeared
// will again be made to be hidden.
$("#ourHideButton").click(function(){
$(".hideable").hide();
});
// As you saw in the CLASS versus ID example, though, a search for
// CLASS is very inefficient
// If this button is pressed often, it could lead to a slow response
// Instead of the above example, you should write your code like this
var hideable;
$("#ourHideButton").click(function(){
if (hideable)
hideable.hide();
else
hideable = $(".hideable").hide();
});
// You can cache your search in a JavaScript variable and reuse it every time
// the button is pressed. Because jQuery almost always returns the
// jQuery object, you can save it the first time it is called for future use
更多精彩
赞助商链接