Some practical jQuery skills

Source: Internet
Author: User

JQuery has now become the most popular JavaScript library in Web development. With jQuery and a large number of plug-ins, you can easily achieve a variety of brilliant results. This article will introduce some practical skills and hope to help you use jQuery more efficiently. Tip 1: use the latest version of jQuery. Each new version includes some performance optimization and bug fixes. To facilitate the upgrade, you can use the jQuery library hosted by the Google CDN service. There are two methods: contains a specific version of the Html code <script src = "http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"> </script> contains the latest version of a branch (In this method, the jQuery version has a cache duration of only one hour, html code <script src = "http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"> </script> Tip 2: Getting DOM elements before using a simple selector typically uses jQuery's getElementById (), getElementsByTagName () and getElementsByClassName () methods. Currently, all mainstream browsers support querySelectorAll (). This method can understand the CSS queryer. You should try this better method. Javascript code $ ('Li [data-selected = "true"] A') // looks good, but slow $ ('Li. selected A') // better method $ ('# ElementID) // best Tip 3: cache jQuery results. If you have no other options, you can only use the DOM selector, then you should cache jQuery results. For example, Javascript code var selectedListItem = $ ('Li [data-selected = "true"] A') Now, jQuery results have been cached to the variable "selectedListItem ", this variable can be used multiple times without affecting performance. Tip 4: Notes for using jQuery extension selectors jQuery provides a large number of extension selectors, such as visible,: hidden, and: animated, which are not valid CSS3 selectors. If you use these selectors, you cannot use the querySelectorAll () method. To avoid this situation, you can first select elements and then filter them. Example: Javascript code $ ('a. button: Den den '); // you cannot use querySelectorAll () $ ('a. button '). filter (': Den den'); // the above results are the same in the best solution, but the 2nd results are faster. Tip 5: the result of running a selector using a jQuery object like an array is a jQuery object. However, jQuery can make the results look more like an array, and you can define the index element and length. Javascript code var buttons = $ ('# navigation. button '); // Selecting all the navigation B // Selecting all the navigation buttons // We can loop though the collection: for (var I = 0; I <buttons. length; I ++) {console. log (buttons [I]); // A DOM element, not a jQuery object} if you want to achieve higher performance, you can use A simple loop (or while Statement) to replace $. each (), which is several times faster than before. Tip 6: the only way to check whether an element exists and whether an element set exists or contains an element is to check the element length. Javascript code If (buttons. length) {// True only if buttons contains elements // Do something} Tip 7: Create a jQuery empty object and create a new jQuery object. Sometimes the overhead is relatively high. However, you can create an empty object and then fill it with add. Javascript code var container = $ ([]); container. add (another_element); Tip 8: count the number of DOM elements on a Web page. If the page contains a large number of elements or content, the browser will take more time to render the page. You can run the following statement on the console to count the number of DOM elements on the page: Javascript code console. log ($ ('*'). length); if the value is small, the page rendering is faster. You can optimize it by deleting unnecessary tags and unnecessary elements. Tip 9: Convert your code into a jQuery plug-in. If you want to encapsulate your jQuery code into a jQuery plug-in for future reuse, you can create it using the following code: javascript code function ($) {$. fn. yourPluginName = function () {// Your code goes here return this ;}}) (jQuery); Tip 10: local storage is an API used to store information on the client. During use, you only need to use your data as an attribute of the localStorage Global Object: Javascript code localStorage. someData = "This data is going to persist upload SS page refreshes and browser restarts"; the old browser does not support This API, but there are various jQuery plug-ins that can be used as an alternative. These plug-ins provide other storage solutions when localStorage is unavailable. The following is an example: Javascript code // Check if "key" exists in the storage. var value = $. jStorage. get ("key"); if (! Value) {// if not-load the data from the server value = load_data_from_server (); // and save it $. jStorage. set ("key", value); Tip 11: Live event processing sets an event handler for any element that matches the selector, even if it is added to the DOM after the initial Page is loaded: javascript code $ ('button. yourclassname '). live ('click', yourFunctionName); in this way, when elements are loaded using ajax or javascript, the event handler automatically sets these elements: Javascript code $ ('button. yourclassname '). die ('click', yourFunctionName); although the live event handler has some limitations It is applicable in most cases. Live Events support jQuery 1.3 and later versions. Tip 12: clone an object. clone () method to Clone the DOM object in JavaScript: Javascript code // clone the DIV var cloned =$ ('# yourdivID '). clone ();. the clone () method cannot clone JavaScript objects. To clone a JavaScript Object, you can use the following code: Javascript code // Shallow copy var newObject = jQuery. extend ({}, oldObject); // Deep copy var newObject = jQuery. extend (true, {}, oldObject); Tip 13: test whether the hidden element passes. hide () and. the show () method can change the visibility of elements. Use the following code to check whether the element is visible: Javascript code if ($ (element ). is (": visible") = "true") {// The element is Visible} Tip 14: find the nearest parent DIV. If you want to find the parent DIV of an element (whether the DIV has an ID or not), you can use this jQuery selector: javascript code $ ("# yourControl "). closest ("div ");

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.