是将jQuery元素存储在变量中更有效吗? [英] Is storing jQuery elements in variables more efficient?

查看:57
本文介绍了是将jQuery元素存储在变量中更有效吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请问哪个更有效?

var myElement = $("#the-name-of-my-element")

myElement.doSomethingOnce;
myElement.doSomethingTwice;
...
myElement.doSomethingTenTimes;

$("#the-name-of-my-element").doSomethingOnce;
$("#the-name-of-my-element").doSomethingTwice;
...
$("#the-name-of-my-element").doSomethingTenTimes;

我有一个页面,其中html元素与JS有许多不同的,有时是重复的交互,所以我想知道是否将该元素存储在变量中可以防止多个jQuery查询".

I have a page in which the html elements have many varied and sometimes repeated interactions with the JS so I'm wondering if storing the element in a variable prevents multiple jQuery "queries".

由于我的项目是一个网络应用程序,所以我很想调整浏览器的功能.

As my project is a web app, I'm keen to tune up what I can for the browser.

推荐答案

缓存节点始终是一个好习惯. JS引擎用来定位节点的工作量比用于存储节点的内存要昂贵得多(当然,除非您要存储大量的DOM树或其他东西).

It is always good practice to cache your nodes. The amount of work the JS engine has to do to locate the nodes is more expensive than the memory that you will use storing the node (of course unless you are storing a massive DOM tree or something).

所以胜利者是:

var myElement = $("#the-name-of-my-element")

myElement.doSomethingOnce;
myElement.doSomethingTwice;
...
myElement.doSomethingTenTimes;

这篇关于是将jQuery元素存储在变量中更有效吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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