Learn about jquery techniques to improve your code (personally think that jquery Handbook is pretty good) _jquery

Source: Internet
Author: User
Tags wrapper

2. Test if the jquery wrapper set contains some elements
If you want to test whether a jquery wrapper set contains elements, you can first try to verify that the first element exists:
Copy Code code as follows:

if ($ (selector) [0]) {...}
Or so
if ($ (selector). Length) {...}

Take a look at this example:
Copy Code code as follows:

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 will return true, because we have two
The input field matches the selector, so the <statement> code will execute
if ($ (' #shopping_cart_items input.in_stock ') [0]) {<STATEMENT>}

3. Read jquery latest version from jquery.org
You can use this code to read the latest version of jquery's code file.

<script src= "Http://code.jquery.com/jquery-latest.js" ></script>
You can use this method to invoke the most recent version of the jquery framework, and of course you can use the following code to invoke 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. Storing data
By using the data method, you can avoid storing it in the DOM, and some front-end development ER prefers to use HTML attributes to store data:
Copy Code code as follows:

$ (' selector '). attr (' Alt ', ' data being stored ');
You can then read data like this:
$ (' selector '). attr (' Alt ');

Using the "alt" attribute to store data as a parameter name is actually not semantic for HTML, we can use the jquery data method to store data for an element in the page:
Copy Code code as follows:

$ (' selector '). Data (' parameter name ', ' data to be stored ');
After that, you get the data:
$ (' selector '). Data (' parameters ');

This data method allows you to make your own data parameters, more semantically more flexible, and you can store data information on any element of the page. For more information on the data () and Removedata () methods, you can see the jquery official explanation

The classic application of this method is to give the input field a default value and then empty it in focus:
HTML section:
Copy Code code as follows:

<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>

Javasript section:
Copy Code code as follows:

$ (function () {
Remove the input field with the clear class
(Note: "Clear once" is two class clear and once)
$ (' #testform input.clear '). each (function () {
Using the data method to store the information
$ (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, and empty if the same
if ($.trim (this). val ()) = = $ (this). Data ("TXT")) {
$ (this). Val ("");
}
}). blur (function () {
Add blur time to the domain with class clear to restore default values
But if class is once, ignore the
if ($.trim (this). val ()) = = "" &&!$ (This). Hasclass ("Once")) {
Restore saved Data
$ (this). Val ($ (this). Data ("TXT"));
}
});
});

5.jQuery Manual standing by side
Most people have trouble remembering all the programming details, and even a good programmer will have an oversight of a program's language, so it's definitely better to improve programming efficiency by printing the relevant manuals or at any time on the desktop.
Oscarotero jquery 1.3 (Wallpaper edition)

6. Record jquery at the Firebug console
Firebug is one of my favorite browser extensions, a tool that allows you to quickly understand the html+css+javascript of the current page in a visual interface, and to complete instant development under that tool. As a jquery or JavaScript developer, Firefox is also supported for documenting your JavaScript code.

The simplest way to write to the Firebug console is as follows:
Console.log ("Hello World")


You can also write some parameters in the way you want them to:

Console.log (2,4,6,8, "foo", bar)
You can also write a small extension to record the JQuery object to the console:

Copy Code code as follows:

JQuery.fn.log = function (msg) {
Console.log ("%s:%o", MSG, this);
return this;
};

For this extension, you can use the. log () method directly to record the current object to the console.
Copy Code code as follows:

$ (' #some_div '). Find (' Li.source > Input:checkbox ')
. log ("Sources to uncheck")
. Removeattr ("checked");

7. Use ID selector whenever possible
After using jquery, you'll find it pretty straightforward to use the class attribute to select the DOM element. Nevertheless, it is recommended that you use the class selector as little as possible instead of using a faster ID selector (IE browser uses the class selector to return a matching class wrapper after traversing the entire DOM tree). The ID selector is faster because the DOM itself has the "natural" getElementById method, and class does not. So if you use the class selector, the browser traverses the entire DOM, and if your Web page DOM structure is complex enough, these class selectors are enough to drag the page slower and faster. Let's take a look at this simple HTML code:
Copy Code code as follows:

<div id= "Main" >
<form method= "POST" action= "/" >
...
...
<input class= "button" id= "Main_button" type= "Submit" value= "Submit"/>
</form>
</div>//using class to invoke the Submit button is much slower than using an absolute ID selector
var Main_button = $ (' #main. Button ');
var Main_button = $ (' #main_button ');

8. Good at using the jquery chain
The jquery chain not only allows you to write powerful operations in a concise way, but also improves development efficiency because it enables you to apply multiple commands to a wrapper set without having to recalculate the wrapper set. So that you don't have to write again:
Copy Code code as follows:

<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 to do simple things:
Copy Code code as follows:

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");
[HTML]
9. Bind the jquery function to $ (window). Load Event
Most jquery instances or tutorials tell us to bind our jquery code to $ (document). Ready event. Although $ (document). The Ready event is OK in most cases, but its parsing order is when the document is ready and the pictures in a single document are being downloaded. So at some point use $ (document). Ready events do not necessarily achieve the desired effect, such as some visual effects and animations, drag and drop, pre-read hidden pictures ... By using the $ (window). The Load event is safe to start running the code you expect after the entire document is ready.
[Code]
$ (window). Load (function () {
Place the code you want to run after the page is completely ready
});

10. Use the jquery chain to qualify selectors to make your code simpler and more elegant
Because JavaScript supports chain structure and supports break lines, your code can be written as follows, this example first removes a class from the element and then adds another class on the same element:
Copy Code code as follows:

$ (' #shopping_cart_items input.in_stock ')
. Removeclass (' In_stock ')
. addclass (' 3-5_days ');

If you want to make it simpler and more practical, you can create a jquery function that supports the chain structure:
Copy Code code as follows:

$.fn.makenotinstock = function () {
return $ (this). Removeclass (' In_stock '). addclass (' 3-5_days ');
}
$ (' #shopping_cart_items input.in_stock '). Makenotinstock (). log ();

11. Use callback function to synchronize effect
If you want to make sure that an event or animation effect is called after another event is run, you will need to use the callback function. You can bind the callback function after these animation effects: Slidedown (speed, [callback]) ie. $ (' #sliding '). Slidedown (' Slow ', function () {...) Click here to preview this example.
Copy Code code as follows:

<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 jquery click events to change visual effects and turn on sliding effects
$ ("Div.button"). Click (function () {
Div.button now appears to be pressing the effect
$ (this). CSS ({borderStyle: "inset", cursor: "Wait"});
#sliding will now fade and turn on the fade effect after completing the action
Slideup once it completes
$ (' #sliding '). Slidedown (' Slow ', function () {
$ (' #sliding '). Slideup (' Slow ', function () {
The CSS property of the button will change when the fade effect is complete
$ (' Div.button '). CSS ({borderStyle: "outset", cursor: "Auto"});
});
});
});
});

12. Learn to use a custom selector
jquery allows us to define our custom selectors on the basis of CSS selectors to make our code simpler:
Copy Code code as follows:

$.expr[': '].mycustomselector= function (element, index, meta, stack) {
Element-dom element
Index-the indexed value currently traversed in the stack
Meta-data about your selector
Stack-used to iterate through the stacks of all elements

Returns true if the current element is included
Returns False if the current element is not included
};

Application of Custom selector:
$ ('. Someclasses:test '). dosomething ();

Let's take a look at a small example where we lock the set of elements with the "rel" attribute by using a custom selector:
Copy Code code as follows:

$.expr[': '].withrel = function (Element) {
var $this = $ (element);
Returns only elements that are not empty for the Rel property
Return ($this. attr (' rel ')!= ');
};

$ (document). Ready (function () {
The use of a custom selector is simple, and it returns an element wrapper set, like other selectors
You can use formatting methods for him, such as the following to 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-loading pictures
It is usually a good idea to use JavaScript to preload a picture:
Copy Code code as follows:

function that defines a preloaded picture list (with parameters)
Jquery.preloadimages = function () {
Traversing pictures
for (var i = 0; i<arguments.length; i++) {
JQuery ("
}
}
You can use preload functions like this
$.preloadimages ("Images/logo.png", "Images/logo-face.png", "images/mission.png");

14. Test your code in good condition
jquery has a framework called the Qunit Unit test. Writing tests is easy, it allows you to safely modify your code, and make sure it still works as expected. Here's how it works:
Copy Code code as follows:

Divide the test into several modules.
Module ("Module B");

Test ("Some other test", function () {
Specifies how many decision statements need to be added to the test.
Expect (2);

Equals (True, false, "failing test");
Equals (True, true, "passing Test");
});

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.