jquery和CSS中的最快选择器方法 - ID还是不? [英] Fastest selector method in jquery and CSS - ID or not?

查看:145
本文介绍了jquery和CSS中的最快选择器方法 - ID还是不?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

jquery / javascript中最快的是什么?

$('#myID .myClass')

$('.myClass')

CSS?

#myID .myClass{}

.myClass{}

我现在看到我应该更好地解释。抱歉!

Ofceauce ID是CSS和JavaScript中更快的选择器。但有些时候你需要使用类,因为有多个选择器。

Ofceauce ID is a faster selector in both CSS and JavaScript. But some times you need to use class since there are multiple selectors.

说的例子,我有i BIG html文档。在页面中间有:

Say forexample that I have i BIG html document. In the middle of the page I have:

<div id="myID">

<a class="myClass">link1</a>

<a class="myClass">link1</a>

<a class="myClass">link1</a>

</div>

如果我要定位所有myClass。那么,在定位类之前定位ID是否更好? (然后我不必对整个HTML文档做domtravel)例如:

If I want to target all "myClass". Would it then be better to target the ID before targeting the classes? (then I wouldn't have to do domtravel of the entire HTML document) Eg.:

这将是:

$('#myID')。find('。myClass')

$('#myID').find('.myClass')

速度比:

$('。myClass')

$('.myClass')

推荐答案

我的测试在现代浏览器上建议您应该使用

My testing on modern browsers suggests that you should go with either,

$('#id').find('.class') // or
$('.class')

不是

$('#id .class')

原因是所有现代浏览器都实现 getElementsByClassName 导致通过类名称(假设哈希实现)的几乎恒定的时间查找。哪些浏览器是现代的是另一个主观问题。

Reason being that all modern browsers implement getElementsByClassName resulting in almost-constant time lookups by class name (assuming a hash implementation). Which browsers are modern is another subjective question.

这篇关于jquery和CSS中的最快选择器方法 - ID还是不?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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