50 essential and practical jQuery code segments and 50 essential jquery code segments

Source: Internet
Author: User

50 essential and practical jQuery code segments and 50 essential jquery code segments

50 essential and practical jQuery code segments

 

This article will show you 50 jquery code snippets that can help your javascript project. Some of the code segments are supported since jQuery1.4.2, while others are actually useful functions or methods. They can help you complete things quickly and well. These are code segments with the best performance I can remember. If you find anything better, paste your version in the comments! I hope you can find something helpful in this article.

1. How to Create nested filters:

// Allows you to reduce the filter of matching elements in the set,
// Only the parts that match the given selector are left. In this case,
// The query has deleted any (: not) with (: has)
// Contains child nodes whose class is "selected" (. selected.
. Filter (": not (: has (. selected ))")
2. How to reuse element search

Var allItems = $ ("div. item ");
Var keepList = $ ("div # container1 div. item ");
// Now you can continue to work with these jQuery objects. For example,
// Crop the "keep list" based on the check box, and the name of the check box
// Meet
<DIV> class names:
$ (FormToLookAt + "input: checked"). each (function (){
KeepList = keepList. filter ("." + $ (this). attr ("name "));
});
</DIV>
3. Any use of has () to check whether an element contains a class or element:

// JQuery. * contains support for this has method. Find this method
// Whether an element contains another element class or any other element
// What you are looking for and want to operate on.
$ ("Input"). has (". email"). addClass ("email_icon ");
4. How to Use jQuery to switch between style sheets

// Find the media type you want to switch to, and then set href to a new style sheet.
$ ('Link [media = 'screen'] '). attr ('href', 'Alternative.css ');
5. How to limit the selection range (for optimization purposes ):

// Use the label name as the class name prefix whenever possible,
// JQuery does not need to spend more time searching.
// The elements you want. Remember that,
// The more specific the operations on the elements on your page,
// The lower the execution and search time.
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_stock"/> Item X </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 correctly use ToggleClass:

// Toggle class allows you
// Whether the class exists to be added or deleted.
// In this case, some developers use:
A. hasClass ('bluebutton ')? A. removeClass ('bluebutton'): a. addClass ('bluebutton ');
// ToggleClass allows you to use the following statements to easily achieve this
A. toggleClass ('bluebutton ');
7. How to set the unique features of IE:

If ($. browser. msie ){
// Internet Explorer is crazy.
}
8. How to Use jQuery to replace an element:

$ ('# Thatdiv'). replaceWith ('fnuh ');
9. How to verify whether an element is null:

If ({('{keks'}.html ()){
// Nothing is found;
}
10. How to Find the index number of an element from an unsorted set

$ ("Ul> li"). click (function (){
Var index = $ (this). prevAll (). length;
});

11. How to bind a function to an event:

$ ('# Foo'). bind ('click', function (){
Alert ('user clicked on "foo ."');
});
12. How to append or add html to an element:

$ ('# Lal'). append ('sometext ');
13. How to Use literal to define attributes when creating elements

Var e = $ ("", {href: "#", class: "a-class another-class", title :"..."});
14. How to use multiple attributes for filtering

// When many similar input elements have different types,
// This precision-based method is very useful.
Var elements = $ ('# someid input [type = sometype] [value = somevalue]'). get ();
15. How to Use jQuery to pre-load images:

JQuery. preloadImages = function (){
For (var I = 0; I <arguments. length; I ++ ){
$ ("}
};
// Usage
Pai.preloadimages('image1.gif ','/path/to/image2.png ', 'some/image3.jpg ');
16. How to Set Event Handlers for any element that matches the selector:

$ ('Button. someClass '). live ('click', someFunction );
// Note: In jQuery 1.4.2, the delegate and undelegate options
// Be introduced to replace live because they provide better context support
// For example, in table, you used
//. Live ()
$ ("Table"). each (function (){
$ ("Td", this). live ("hover", function (){
$ (This). toggleClass ("hover ");
});
});
// Used now
$ ("Table"). delegate ("td", "hover", function (){
$ (This). toggleClass ("hover ");
});
17. How to find a selected option element:

$ ('# SomeElement'). find ('option: selected ');
18. How to hide an element that contains a value text:

$ ("P. value: contains ('thetextvalue')"). hide ();
19. If it is automatically rolled to a certain area of the page

JQuery. fn. autoscroll = function (selector ){
$ ('Html, body'). animate (
{ScrollTop: $ (selector). offset (). top },
500
};
}
// Then scroll to the class/area you want to go.
$ ('. Area_name'). autoscroll ();
20. How to detect various browsers:

Detect Safari (if ($. browser. safari )),
Check IE6 and later versions (if ($. browser. msie & $. browser. version> 6 )),
Check IE6 and earlier versions (if ($. browser. msie & $. browser. version <= 6 )),
Check FireFox 2 and later versions (if ($. browser. mozilla & $. browser. version> = '1. 8 '))
21. How to replace words in a string

Var el = $ ('# id ');
El.html(el.html (). replace (/word/ig ,''));
22. How to disable context menu by right-clicking:

$ (Document). bind ('textmenu ', function (e ){
Return false;
});
23. How to define a custom Selector

$. Expr [':']. mycustomselector = function (element, index, meta, stack ){
// Element-a DOM element
// Index-the current cyclic index in the stack
// Meta-metadata about the selector
// Stack-stack of all elements to be recycled
// Returns true if it contains the current element.
// If the current element is not included, false is returned };
// Custom selector usage:
$ ('. SomeClasses: test'). doSomething ();
24. How to check whether an element exists

If ($ ('# somediv'). length ){
// Long live !!! It exists ......
}
25. How to Use jQuery to detect two situations: Right-click and left-click:

$ ("# 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 display or delete the default values in the input field

// This Code shows that when the user does not enter a value,
// How to retain data in text input fields
// A default value
Wap_val = [];
$ (". Swap"). each (function (I ){
Wap_val [I] = $ (this). val ();
$ (This). focusin (function (){
If ($ (this). val () = swap_val [I]) {
$ (This). val ("");
}
}). Focusout (function (){
If ($. trim ($ (this). val () = ""){
$ (This). val (swap_val [I]);
}
});
});
27. How to automatically hide or disable elements after a period of time (version 1.4 is supported ):

// This is implemented using setTimeout in 1.3.2.
SetTimeout (function (){
$ ('. Mydiv'). hide ('blind', {}, 500)
},5000 );
// This method can be implemented using the delay () function in 1.4 (this is like sleep)
$ (". Mydiv"). delay (5000). hide ('blind', {}, 500 );
28. How to dynamically Add the created elements to the DOM:

Var newDiv = $ ('');
NewDiv. attr ('id', 'mynewdiv '). appendTo ('body ');
29. How to limit the number of characters in the Text-Area field:

JQuery. fn. maxLength = function (max ){
This. each (function (){
Var type = this. tagName. toLowerCase ();
Var inputType = this. type? This. type. toLowerCase (): null;
If (type = "input" & inputType = "text" | inputType = "password "){
// Apply the standard maxLength
This. maxLength = max;
}
Else if (type = "textarea "){
This. onkeypress = function (e ){
Var ob = e | event;
Var keyCode = ob. keyCode;
Var hasSelection = document. selection? Document. selection. createRange (). text. length> 0: this. selectionStart! = This. selectionEnd;
Return! (This. value. length >=max & (keyCode> 50 | keyCode = 32 | keyCode = 0 | keyCode = 13 )&&! Ob. ctrlKey &&! Ob. altKey &&! HasSelection );
};
This. onkeyup = function (){
If (this. value. length> max ){
This. value = this. value. substring (0, max );
}
};
}
});
};
// Usage
$ ('# Mytextarea'). maxLength (500 );
30. How to create a basic test for a function

// Put the test in the module separately
Module ("Module B ");
Test ("some other test", function (){
// Specify the number of assertions to be run in the test.
Secondary CT (2 );
// A comparison assertEquals of JUnit
Equals (true, false, "failing test ");
Equals (true, true, "passing test ");
});
31. In jQuery, how can I get an element:

Var cloned = $ ('# somediv'). clone ();
32. How to test whether an element is visible in jQuery?

If ($ (element). is (': visible') = 'true '){
// This element is visible.
}
33. How to place an element in the center of the screen:

JQuery. fn. center = function (){
This.css ('position', 'absolute ');
This.css ('top', ($ (window). height ()-this. height ()/+ $ (window). scrollTop () + 'px ');
This.css ('left', ($ (window). width ()-this. width ()/2 + $ (window). scrollLeft () + 'px ');
Return this;
}
// Use the above function in this way:
$ (Element). center ();
34. How to put the values of all elements with a specific name in an array:

Var arrInputValues = new Array ();
$ ("Input [name = 'table [] ']"). each (function (){
ArrInputValues. push ($ (this). val ());
});
35. How to remove HTML from elements

(Function ($ ){
$. Fn. stripHtml = function (){
Var regexp =/<("[^"] * "| '[^'] * '| [^'">]) *>/gi;
This. each (function (){
Certificate (this).html (certificate (this).html (). replace (regexp ,""));
});
Return $ (this );
}
}) (JQuery );
// Usage:
$ ('P'). stripHtml ();
36. How to Use closest to obtain the parent element:

$ ('# Searchbox'). closest ('div ');
37. How to Use Firebug and Firefox to record jQuery Event Logs:

// Enable chained Logging
// Usage:
$ ('# Somediv'). hide (). log ('div den'). addClass ('someclass ');
JQuery. log = jQuery. fn. log = function (msg ){
If (console ){
Console. log ("% s: % o", msg, this );
}
Return this;
};
38. How to force the link to be opened in the pop-up window:

JQuery ('A. popup'). live ('click', function (){
Newwindow = window. open ($ (this). attr ('href '), '', 'height = 200, width = 150 ');
If (window. focus ){
Newwindow. focus ();
}
Return false;
});
39. How to force the link to open in a new tab:

JQuery ('A. newTab '). live ('click', function (){
Newwindow = window. open ($ (this). href );
Jquery(thisdomain.tar get = "_ blank ";
Return false;
});
40. How to Use. siblings () in jQuery to select peer Elements

// Do not do this
$ ('# Nav li'). click (function (){
$ ('# Nav li'). removeClass ('active ');
$ (This). addClass ('active ');
});
// The alternative method is
$ ('# Nav li'). click (function (){
$ (This). addClass ('active'). siblings (). removeClass ('active ');
});
41. How to switch all check boxes on the page:

Var tog = false;
// Or true, if they are selected during loading
$ ('A'). click (function (){
$ ("Input [type = checkbox]"). attr ("checked ",! Tog );
Tog =! Tog;
});
42. How to filter an element list based on some input text:

// If the element value matches the input text
// This element will be returned
$ ('. SomeClass'). filter (function (){
Return $ (this). attr ('value') =$ ('input # someid'). val ();
})
43. How to obtain the mouse pad position x and y

$ (Document). ready (function (){
$ (Document). mousemove (function (e ){
('{Xy'{.html ("X Axis:" + e. pageX + "| Y Axis" + e. pageY );
});
});
44. How to change the entire List Element (LI) to clickable

$ ("Ul li"). click (function (){
Window. location = $ (this). find ("a"). attr ("href ");
Return false;
});
<Ul>
<Li> <a href = "#"> Link 1 </a> </li>
<Li> <a href = "#"> Link 2 </a> </li>
<Li> <a href = "#"> Link 3 </a> </li>
<Li> <a href = "#"> Link 4 </a> </li>
</Ul>
45. How to Use jQuery to parse XML (basic example ):

Function parseXml (xml ){
// Locate each Tutorial and print the author
$ (Xml). find ("Tutorial"). each (function (){
$ ("# Output"). append ($ (this). attr ("author") + "");
});
}
46. How to check whether the image has been fully loaded

$ ('# Theimag'). attr ('src', 'image.jpg'). load (function (){
Alert ('this Image Has Been loaded ');
});
47. How to Use jQuery to specify a namespace for an event:

// Events can be bound to namespaces in this way
$ ('Input'). bind ('blur. valider', function (e ){
//...
});
// The data method also accepts the namespace
$ ('Input'). data ('validation. isvalid', true );
48. How to check whether cookies are enabled

Var dt = new Date ();
Dt. setSeconds (dt. getSeconds () + 60 );
Document. cookie = "cookietest = 1; expires =" + dt. toGMTString ();
Var cookiesEnabled = document. cookie. indexOf ("cookietest = ")! =-1;
If (! CookiesEnabled ){
// No cookie is enabled
}
49. How to Make the cookie expire:

Var date = new Date ();
Date. setTime (date. getTime () + (x * 60*1000 ));
$. Cookie ('example ', 'foo', {expires: date });
50. How to use a clickable link to replace any URL on the page

$. Fn. replaceUrl = function (){
Var regexp =/(ftp | http | https): \/(\ w +: {0, 1} \ w *@)? (\ S +) (: [0-9] + )? (\/| \/([\ W #! :.? + = & % @! \-\/])?) /Gi;
This. each (function (){
Certificate (this).html (
Parameters (this).html (). replace (regexp, '<a href = "$1"> $1 </a> ')
);
});
Return $ (this );
}
// Usage
$ ('P'). replaceUrl ();

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.