gpt4 book ai didi

javascript - id vs 类选择基准

转载 作者:技术小花猫 更新时间:2023-10-29 12:39:12 25 4
gpt4 key购买 nike

有没有人用 CSS 和 javascript 中的 id 和 class 标记选择元素?

选择具有 id 的元素比具有类的元素更快是有道理的,即使它是唯一具有该类的元素也是如此。

我真的需要担心吗?

最佳答案

当搜索 id 时,选择器会在找到匹配项后立即停止(即使有很多匹配项)——我假设有某种用于此目的的键/值查找表,因为它比 DOM 遍历快得多。 Here's why ,这是摘录:

It's still much better to select by ID...because jQuery uses the browser's native method (getElementByID) to do this and doesn't have to do any of it's own DOM traversal, which is much faster.

那里的链接结果显示 idclass 相比速度提高了 100 倍。

当搜索一个 class 时,会搜索整个 DOM(或作用域)。 Here's a benchmark using scope .

您可以在自己的浏览器中对选择器进行基准测试 here .

关于javascript - id vs 类选择基准,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2559934/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com