jQuery是否对“选择器"进行某种形式的缓存? [英] Does jQuery do any kind of caching of "selectors"?

查看:145
本文介绍了jQuery是否对“选择器"进行某种形式的缓存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,第一段代码会执行两次完整搜索吗?如果没有发生DOM更改,是否足够聪明地缓存结果?

For example, will the first piece of code perform a full search twice, or is it smart enough to cache results if no DOM changes have occurred?

if ($("#navbar .heading").text() > "") {
  $("#navbar .heading").hide();
}

var $heading = $("#navbar .heading");

if ($heading.text() > "") {
  $heading.hide();
}

如果选择器更复杂,我可以想象这是一个不小的成功.

If the selector is more complex I can imagine it's a non-trivial hit.

推荐答案

jQuery没有,但是有可能在表达式中分配变量,然后在后续表达式中重用它们.因此,对您的示例进行缓存处理...

jQuery doesn't, but there's the possibility of assigning to variables within your expression and then use re-using those in subsequent expressions. So, cache-ifying your example ...

if ((cached = $("#navbar .heading")).text() > "") {
  cached.hide();
}

不利的一面是它使代码更加笨拙且难以理解.

Downside is it makes the code a bit fuglier and difficult to grok.

这篇关于jQuery是否对“选择器"进行某种形式的缓存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆