Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to avoid repeated selections in jQuery

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article is to share with you about how jQuery can avoid repeated choices. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

Avoid repetitive selection

It is rare to reuse the same selector twice. The following code selects each p tag three times:

Css ("color", "blue"); $("p") .css ("font-size", "1.2em"); $("p") .text ("Text changed!")

Remember that jQuery supports chained operations; multiple methods can be applied to the same collection. Therefore, code with the same effect can be rewritten with a single selector:

("p") .css ({"color": "blue", "font-size": "1.2em"}) .text ("Text changed!")

If you need to use the same set of elements multiple times, you should cache the jQuery object with variables, such as:

Var $p = $("p"); $p.css ("color", "blue"); $p.text ("Text changed!")

Unlike standard DOM collections, jQuery collections are not real-time, and objects are not automatically updated when paragraph tags are added or removed from the document. You can take advantage of this limitation to create a DOM collection and pass it to the jQuery function as needed, such as:

Var p = document.getElementByTagName ("p"); $(p) .css ("color", "blue"); / / update the DOM$ (p) .text ("Text changed!"); Thank you for reading! This is the end of the article on "how to avoid repeated choices in jQuery". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report