14 tips for improving jquery code

Source: Internet
Author: User
Document directory
  • 1. Test and improve your jquery selector level
  • 2. test whether the jquery package set contains certain elements.
  • 3. Read the latest jquery version from jquery.org
  • 4. Store Data
  • 5. jquery Manual
  • 6. Record jquery In the firebug Console
  • 7. Use the ID selector whenever possible
  • 8. good at using jquery chain
  • 9. Bind The jquery function to the $ (window). Load event.
  • 10. Use jquery chain to limit selector, making your code more concise and elegant
  • 11. Use the callback function to synchronize results
  • 12. Learn to use a custom Selector
  • 13. Pre-load images
  • 14. Test your code in good condition.

Jquery is easy to learn, but if you want to write more beautiful, more concise, and more efficient code, you always need some skills. This article summarizes14 tips for improving jquery code.

1. Test and improve your jquery selector level

This jquery selector lab is very cool and can be used online for free. Of course, you can also use it offline locally. This test page contains complex HTML combination fields, and then you can try to use various jquery selectors predefined. If this is not enough, you can also customize the selector.

2. test whether the jquery package set contains certain elements.

If you want to test whether a jquery packaging set contains certain elements, You can first verify whether the first element exists:

If ($ (selector) [0]) {...} // or so if ($ (selector). Length ){...}

Let's take a look at this example:

// Example. if your page has the following HTML code <ul id = "shopping_cart_items"> <li> <input class = "in_stock" name = "item" type = "radio" value = "item -X "/> Item x </LI> <li> <input class =" unknown "name =" item "type =" radio "value =" item-y "/> item Y </LI> <li> <input class = "in_stock" name = "item" type = "radio" value = "item-z"/> item z </Li> </ul> <PRE escaped = "true" lang = "JavaScript">... // This if condition returns true because two // input fields match the selector. Therefore, the <Statement> code will execute if ($ ('# shopping_cart_items input. in_stock') [0]) {<Statement>}
3. Read the latest jquery version from jquery.org

You can use this code to read the code file of the latest jquery version.

<script src="http://code.jquery.com/jquery-latest.js"></script>

You can use this method to call the latest version of jquery framework. Of course, you can also use the following code to call the same latest version of jquery from ajax.googleapis.com:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"type="text/javascript"></script>
4. Store Data

Using the data method can avoid storing data in the Dom. Some front-end developers prefer to use HTML attributes to store data:

$ ('Selector '). ATTR ('alt', 'Data being stored'); // you can read the data as follows: $ ('selector '). ATTR ('alt ');

Using the "Alt" attribute to store data as a parameter name is not semantic for HTML. We can use jquery's data method to store data for an element on the page:

$ ('Selector '). data ('parameter name', 'Data to be stored '); // obtain the data as follows: $ ('selector '). data ('parameters ');

This data method allows you to clearly define data parameters and make the semantics more flexible. You can store data information on any element on the page. For more information about the data () and removedata () methods, see the official jquery explanation.

The classic application of this method is to give the input field a default value, and then clear it when focusing:
HTML section:

<form id="testform"><input type="text" class="clear" value="Always cleared" /><input type="text" class="clear once" value="Cleared only once" /><input type="text" value="Normal text" /></form>

Except ript:

$ (Function () {// retrieve the input fields with the clear class // (note: "clear once" is two classes clear and once) $ ('# testform input. clear '). each (function () {// use the data method to store data $ (this ). data ("TXT", $. trim ($ (this ). val ()));}). focus (function () {// determines whether the value in the domain is the same as the default value when the focus is obtained. If the value is the same, the IF ($. trim ($ (this ). val () ===$ (this ). data ("TXT") {$ (this ). val ("");}}). blur (function () {// Add the Blur time for the domain with class clear to restore the default value. // However, if the class is once, ignore if ($. trim ($ (this ). val () = ""& &! $ (This ). hasclass ("once") {// restore saved data $ (this ). val ($ (this ). data ("TXT "));}});});

View demo

5. jquery Manual

It is hard for most people to remember all the programming details. Even a good programmer will be negligent in a certain programming language, therefore, printing related manuals or checking them on the desktop at any time can definitely improve programming efficiency.
Oscarotero jquery 1.3 (wallpaper Version)

6. Record jquery In the firebug Console

Firebug is one of my favorite browser extension tools. This tool allows you to quickly understand the HTML + CSS + JavaScript of the current page on the visual interface, and complete real-time development with this tool. As a jquery or Javascript developer, Firefox also supports recording your JavaScript code.

The simplest way to write data to the firebug console is as follows:

console.log("hello world")

You can also write some parameters as expected:

console.log(2,4,6,8,"foo",bar)

You can also write a small extension to record jquery objects to the console:

jQuery.fn.log = function (msg) {console.log("%s: %o", msg, this);return this;};

For this extension, you can directly use the. Log () method to record the current object to the console.

$('#some_div').find('li.source > input:checkbox').log("sources to uncheck").removeAttr("checked");
7. Use the ID selector whenever possible

After using jquery, you will find it quite easy to use the class attribute to select DOM elements. However, we recommend that you replace the class selector with the ID selector that runs faster as much as possible (using the class selector in IE will return a consistent class packaging set after traversing the entire DOM tree ). The ID selector is faster because the DOM itself has the "natural" getelementbyid method, but the class does not. So if you use the class selector, the browser will traverse the entire DOM. If your webpage Dom structure is complex enough, these class selector will drag the page slowly. Let's take a look at this simple HTML code:

<div id="main"><form method="post" action="/">
// Using the class to call the submit button is much slower than using the absolute ID selector. var main_button =$ ('# Main. button '); var main_button =$ (' # main_button ');
8. good at using jquery chain

The jquery chain not only allows you to write powerful operations in a concise manner, but also improves development efficiency because it can apply multiple commands to the packaging set without re-computing the packaging set. So you don't have to write it like this:

<li>Description: <input type="text" name="description" value="" /></li>
$('#shopping_cart_items input.text').css('border', '3px dashed yellow');$('#shopping_cart_items input.text').css('background-color', 'red');$('#shopping_cart_items input.text').val("text updated");

Instead, you can use the jquery chain for simple operations:

var input_text = $('#shopping_cart_items input.text');input_text.css('border', '3px dashed yellow');input_text.css('background-color', 'red');input_text.val("text updated");//same with chaining:var input_text = $('#shopping_cart_items input.text');input_text.css('border', '3px dashed yellow').css('background-color', 'red').val("text updated");
9. Bind The jquery function to the $ (window). Load event.

Most jquery instances or tutorials tell us to bind our jquery code to the $ (document). Ready event. Although $ (document ). the ready event is okay in most cases, but the parsing sequence starts when the document is ready and images and other objects in a single document are being downloaded. In some cases, using the $ (document). Ready event may not necessarily achieve the expected effect, such as some visual effects and animations, drag and drop, pre-read hidden images, etc... By using the $ (window). Load event, you can safely run your desired code after the entire document is ready.

$ (Window). Load (function () {// put the code you want to run after the page is fully ready });
10. Use jquery chain to limit selector, making your code more concise and elegant

Because JavaScript supports the Link Structure and line breaks, your code can be written as follows. This example first removes a class from the element and then adds another class to the same element:

$('#shopping_cart_items input.in_stock').removeClass('in_stock').addClass('3-5_days');

To make it simpler and more practical, you can create a jquery function that supports the chain structure:

$.fn.makeNotInStock = function() {return $(this).removeClass('in_stock').addClass('3-5_days');}$('#shopping_cart_items input.in_stock').makeNotInStock().log();
11. Use the callback function to synchronize results

If you want to ensure that an event or animation effect is called after another event is run, you need to use the callback function. You can bind the callback number after these animation effects: slidedown (speed, [callback]) IE. $ ('# Sliding '). slidedown ('low', function (){... Click here to preview this example.

<style>div.button { background:#cfd; margin:3px; width:50px;text-align:center; float:left; cursor:pointer;border:2px outset black; font-weight:bolder; }#sliding { display:none; }</style>
$ (Document ). ready (function () {// use the jquery click event to change the visual effect and enable the sliding effect $ ("Div. button "). click (function () {// Div. button now looks like the following example (this).css ({borderstyle: "Inset", cursor: "Wait "}); // # Sliding will gradually hide and enable the gradient effect after the action is completed // slideup once it completes $ ('# Sliding '). slidedown ('low', function () {$ ('# Sliding '). slideup ('low', function () {// After the gradient effect is completed, it will be changed to the following css1_$('div.button').css ({borderstyle: "outset", cursor: "Auto "});});});});});
12. Learn to use a custom Selector

Jquery allows us to define a custom Selector Based on the CSS selector to make our code simpler:

$. Expr [':']. mycustomselector = function (element, index, Meta, stack) {// element-dom element // index-index value currently traversed in the stack // meta-data element about your selector // stack-used to traverse the stacks of all elements // returns true if it contains the current element. // returns false if it does not contain the current element }; // application of the custom selector: $ ('. someclasses: test '). dosomething ();

Let's take a look at a small example. We use a custom selector to lock the element set containing the "rel" attribute:

$. Expr [':']. withrel = function (element) {var $ this = $ (element); // returns only the element return ($ this. ATTR ('rel ')! = '') ;}; $ (Document ). ready (function () {// the usage of the custom selector is very simple. Like other selectors, it returns an element package set // you can use the format Method for it, for example, modify its CSS style $ ('a: withrel').css ('background-color', 'green ');});
<ul><li><a href="#">without rel</a></li><li><a rel="somerel" href="#">with rel</a></li><li><a rel="" href="#">without rel</a></li><li><a rel="nofollow" href="#">a link with rel</a></li></ul>
13. Pre-load images

Usually, it is quite good to use JavaScript to pre-load images:

// Defines the function (with parameters) of the pre-loaded image list jquery. preloadimages = function () {// traverse the image for (VAR I = 0; I <arguments. length; I ++) {jquery (" "). ATTR ("src", arguments [I]) ;}// you can use the preload function $. preloadimages ("images/logo.png", "images/logo-face.png", "images/mission.png ");
14. Test your code in good condition.

Jquery has a unit test framework named qunit. It's easy to write and test. It allows you to easily modify your code and make sure it still works as expected. The following describes how to work:

// Divide the test into several modules. module ("Module B"); test ("Some other test", function () {// specify the number of judgment statements to be added to the test. round CT (2); equals (true, false, "failing test"); equals (true, true, "Passing test ");});

More jquery and general JavaScript tips to improve your code

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.