在jquery中缓存时,ID选择器比类选择器更快 [英] Is ID selector faster than class selector when it is cached in jquery

查看:91
本文介绍了在jquery中缓存时,ID选择器比类选择器更快的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在Javascript中,ID是一个比类更快的选择器。但是如果我缓存选择器呢?当缓存选择器时,如果它是类选择器,它的速度是否会不同,或者它是否与id选择器一样快?

I know that ID is a faster selector than class in Javascript. But what if I cache the selector? When the selector is cached, would it differ in speed if it’s a class selector, or will it be as fast as the id selector?

示例:

<div class="myclass"></div>
<div id="myid"></div>

var $myclass = $('.myclass');
var $myid = $('#myid');

$ myid会比$ myclass快吗?

Will $myid be faster than than $myclass?

推荐答案

你有那些存储在变量中的东西。所以两者的速度都是一样的。

You have those stored in variables. So the speed will be the same for both.

当您迭代DOM以获取元素时,将会出现性能损失。那时ID选择器将比类选择器快。

The performance hit will occur when you are iterating DOM to get elements. At that time ID selector will be faster than class selector.

这篇关于在jquery中缓存时,ID选择器比类选择器更快的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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