jQuery caching selectors

自古美人都是妖i 提交于 2019-12-10 09:33:04

问题


I have div with id #wrapper and all element are inside it. I'm caching wrapper by doing

var $wrapper = $('#wrapper');

Now any time i want to make a selector or reference an element, i do

$wrapper.find('#whatever').click(....

By doing this i avoid wrapping with jQuery object again, so any selector i do in the future will be based on the cached $wrapper. But on the other when i use find() with the cached $wrapper, i know it will search all elements inside #wrapper. My questions is whic is better better, use cached variable along with find then issue click event, or just simply do $('#whatever').click(..

whatever can be either a class or id.


回答1:


if you use it where whateverID is an ID then $('#whateverID').click(.. would give you slightly better performance, however if whateverCLASS is class or anything other than ID, $wrapper.find('whateverCLASS').click(.... will be better since the traversing will be limited to specific container which is subset of the whole DOM




回答2:


Performance wise it is better to cache the "wrapped" version of the DOM element. Otherwise you'll be traversing the DOM every time you do $("#myElem") which can get very expensive if your DOM is really big or you are doing it a lot of times.




回答3:


The two are not completely equivalent. Your caching version is actually the same as $("#wrapper #whatever"), and won't match the element with id whatever if it isn't contained in the wrapper div.

If you always intend for the #whatever element to be within the #wrapper, then $('#whatever') is actually probably faster than your cached version - finding elements by ID involves a single function call, getElementById, which is available in all browsers, while your cached version involves checking the hierarchy to make sure the matched #whatever element descends from #wrapper.




回答4:


What about $('selector', context) so ...

$('#whatever', $wrapper)

searches the DOM only in the context of $wrapper

Don't search the whole tree when you can search a single branch or twig.



来源:https://stackoverflow.com/questions/5845862/jquery-caching-selectors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!