简体   繁体   English

jQuery选择器性能建议?

[英]Jquery Selector Performance Advice?

I have a very big single html page. 我有一个很大的HTML页面。 I am performing data manipulation to that page. 我正在对该页面执行数据操作。 I am wondering if there is any best way for Jquery selector. 我想知道是否有Jquery选择器的最佳方法。 like 喜欢

$("#id").text("ABC");

Above statement searches for tags in my HTML page, since my HTML is very big. 上面的语句在我的HTML页面中搜索标签,因为我的HTML非常大。 is there any performance tip for that ? 有什么性能提示吗?

for ex: 例如:

Which one is faster ? 哪一个更快?

$(document).on("click", "#contactsTab", callback);

or 要么

$("#contactsTab").on("click", callback);

If you're going to re-use $("#id") , I would store it in a variable and then use that. 如果您要重复使用$("#id") ,我会将其存储在变量中,然后使用它。 Otherwise, you're searching through the DOM each time for that element. 否则,您每次都在DOM中搜索该元素。

var $element = $("#id");
$element.text("ABC");

Searching by id is the fastest dom search. 按ID搜索是最快的dom搜索。 It might be nominally faster to do: 从名义上讲,这样做可能会更快:

document.getElementById("id").innerHTML = "ABC";

An ID selector should have the most optimal of all jQuery selector performances. 在所有jQuery选择器性能中,ID选择器应具有最佳性能。 Ideally you should not have more than one element on the page having that id. 理想情况下,页面上具有该ID的元素不应超过一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM