1

I'm working on some JQuery code and I have a question about caching selectors. I have a certain function that is called when scrolling (and thus needs to be fast). I tried caching the selectors used in the function during the initialization, like so:

var myElement = $('#myElement');

function onScroll()
{
    myElement.whatever();
}

When I profile the code in firebug, I see that the JQuery selector function gets called exactly 5 times as often as the onScroll function (I use 5 different selectors in the function), and is responsible for the majority of execution time.

1) So what exactly is the benefit of caching this way? I'm not being sardonic :)

2) I understand that the selector needs to be re-run in case the DOM changes, but is there any way to cache a single selected object so that the function doesn't need to run each time, while staying within JQuery?

4

1 回答 1

2
  1. 当您使用该变量时,myElement您使用的是一个 jQuery 对象,该对象包含对创建对象时找到的元素的引用。当您使用 jQuery 对象时,选择器不会重新运行以更新元素集。

  2. 是的,你完全按照你所展示的那样做。

于 2012-06-25T22:15:42.733 回答