50 Essential Practical jquery Code Snippets + 15 jquery snippets that can be used directly

Source: Internet
Author: User
Tags tag name
50 Essential Practical jquery Code Snippets 15 jquery Snippets that you can use directlyHttp://www.csdn.net/article/2013-07-16/2816238-15-jQuery-Code-Snippets-for-Developers


This article will show you 50 pieces of jquery code that can help with your JavaScript project. Some of these pieces of code are supported by jQuery1.4.2 and others are really useful functions or methods that can help you get things done quickly and well. If you find anything you can do better, please paste your version in the comments!

1. How to modify the jquery default encoding (for example, default UTF-8 change to GB2312):

$.ajaxsetup ({
	ajaxsettings:{contentType: "application/x-www-form-urlencoded;chartset=gb2312"} 
});


2. Resolve jquery, prototype coexistence, $ global variable conflict problem:

<script src= "Prototype.js" ></script>
<script src= "Http://blogbeta.blueidea.com/jquery.js" > </script>
<script type= "Text/javascript" >
      jquery.noconflict ();

Note: must first introduce prototype.js and then introduce Jquery.js, the order can not be wrong.

3. JQuery determines if an event is bound on an element

The jquery event encapsulation supports determining whether an event is bound on an element, and this method applies only to jquery-bound event
var $events = $ ("#foo"). Data ("events");
if ($events && $events ["click"]) {
//your code


4. How to use jquery to switch style sheets

Find the type of media you want to switch (Media-type), and then set the href to a new style sheet.
$ (' link[media= ' screen ']. attr (' href ', ' alternative.css ');


5. How to limit selection (based on optimization purposes):

Use the tag name as a prefix to the class name whenever possible,
so jquery doesn't need to spend more time searching
//The elements you want. One thing to keep in mind is that the
more specific the operations of the elements on your page are, the
more you can reduce the time to execute and search.
var in_stock = $ (' #shopping_cart_items input.is_in_stock ');

<ul id= "Shopping_cart_items" > <li><input type= "Radio" value= "Item-x" "
name=" Item "class=" Is_in_ The stock "/> Item x</li> <li><input type= Radio" value= "Item-y" name= "
item" class= "3-5_days"/> Item y</li>
<li><input type= "Radio" value= "Item-z" name= "item" class= "Unknown"/> Item z</li >
</ul>


6. How to use Toggleclass correctly:

The Toggle (toggle) class allows you
to add or remove a class based on whether or not it exists.
//In this case some developers use:
a.hasclass (' BlueButton ')? A.removeclass (' BlueButton '): A.addclass (' BlueButton ');
Toggleclass allows you to use the following statement to easily do this
a.toggleclass (' BlueButton ');


7. How to set IE specific features:

if ($.browser.msie) {
//Internet Explorer is a sadist
}


8. How to use jquery to replace an element:

$ (' #thatdiv '). ReplaceWith (' Fnuh ');


9. How to verify that an element is empty:

Method one
if (! $ (' #keks '). HTML ()) {
//nothing found;
}

Method two
if ($ (' #keks '). Is (": Empty")) {
//nothing found;
}


10. How to find the index number of an element from an unordered collection

$ ("ul > Li"). Click (function () {
var index = $ (this). Prevall (). length;//prevall ([expr]): Find all sibling elements
before the current element });


11. How to bind a function to an event:

Method a
$ (' #foo '). Click (Function (event) { 
alert (' User clicked on ' foo. 

'); Method Two, which supports dynamic parameter
$ (' #foo '). Bind (' click ', {test1: "abc", Test2: "123"}, function (event) { 
alert (' User clicked on " Foo. "' + Event.data.test1 + event.data.test2); 


12. How to append or add HTML to the element:


13. How to use object literals (literal) to define attributes when creating elements


14. How to use multiple properties to filter

When using many similar input elements of different types, 
//This method based on precision is useful 


15. How to use jquery to preload an image:

Jquery.preloadimages = function () {for 
(var i = 0; i < arguments.length; i++) { 
$ ("


16. How to set an event handler for any element that matches the selector:

$ (' Button.someclass '). Live (' click ', someFunction); 
Note that in the jquery 1.4.2, the delegate and undelegate options 
//are introduced instead of live because they provide better context support 
//For example, in the case of table, you used to use
$ ("table"  each (function () { 
$ ("TD", this). Live ("hover", function () { 
$ (this). Toggleclass ("hover"); 
}); 
}); 
Now use 
$ ("table"). Delegate ("TD", "hover", function () { 
$ (this). Toggleclass ("hover"); 


17. How to find an option element that has already been selected:


18. How to hide an element that contains the text of a value:


19. How to create a nested filter:

Filters that allow you to reduce the matching elements in the collection,
//Only those parts that match the given selector. In this case,
//The query deletes any child nodes (: Has)
//that contain the class "Selected" (. selected).
. Filter (": Not (: Has (. selected))")


20. How to detect various browsers:

Detect Safari (if ($.browser.safari)),
Detect IE6 and subsequent versions (if ($.browser.msie && $.browser.version > 6)),
Detect IE6 and Previous versions (if ($.browser.msie && $.browser.version <= 6)),
Detects Firefox 2 and later versions (if ($.browser.mozilla && $.browser.version >= ' 1.8 '))

21. Any use of has () to check whether an element contains a class or element:

The JQuery 1.4.* contains support for this has approach.
//This method finds whether an element contains another element class or anything else that you are looking for and that you want to operate on.
$ ("input"). has (". Email"). AddClass ("Email_icon");


22. How to disable right-click context menu:

$ (document). Bind (' ContextMenu ', function (e) {return 
false; 


23. How to define a custom selector

$.expr[': '].mycustomselector = function (element, index, meta, stack) { 
//element- 
The current cyclic index in a DOM element//index– Stack c2/>//meta–/// 
stack– the stack of all elements to loop///If the 
current element is included returns True 
//returns False if the current element is not included; 
Custom Selector Usage: 


24. How to check if an element exists

if ($ (' #someDiv '). Length) { 
//Long live ... It exists ... 


25. How to use jquery to detect two mouse clicks with right and left buttons:

$ ("#someelement"). Live (' click ', Function (e) { 
    if (!$.browser.msie && e.button = 0) | | ($.browser.msie && E.button = 1)) { 
        alert ("Left Mouse button clicked"); 
    } else if (E.button = = 2) { 
        alert ("Right Mouse button clicked"); 
    }
);


26. How to replace the words in a string

var el = $ (' #id '); 


27. How to automatically hide or close elements after a period of time (support version 1.4):

//This is the way we use settimeout to implement in 1.3.2 settimeout (function () {$ ('. Mydiv '). Hide (' blind ', {}, 500)}, 5000); And this is the way you can use the delay () feature in 1.4 (which is much like hibernation) $ (". Mydiv"). Delay (5000). Hide (' blind 

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.