JQuery common instance code snippets (50) developed by web Front-end, webjquery
This article shows 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 part that matches the given selector is left. In this case, // the query deletes any subnodes without (: not) (: has) // containing the class "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. The name of the check box // conforms to <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. This method finds out whether/or not an element contains another element class or any other things that you are looking for and operating 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 prefix of the class name as much as possible. // jQuery does not need to spend more time searching for the elements you want. Remember that the more specific the operations on the elements on your page, the more time it takes 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_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 to add or delete a Class Based on the existence or absence of a class. // In this case, some developers use: a. hasClass ('bluebutton ')? A. removeClass ('bluebutton '):. addClass ('bluebutton '); // toggleClass allows you to use the following statements to easily do this.. toggleClass ('bluebutton ');
7. How to set the unique features of IE
If ($. browser. msie) {// Internet Explorer is actually not that easy to use}
8. How to Use jQuery to replace an element
$(‘#thatdiv').replaceWith(‘fnuh');
9. How to verify whether an element is null
If (items ('{keks'}.html (). trim () {// nothing 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 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 ++) {$ (" "). attr ('src', arguments [I]) ;}}; // usage example .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 that in jQuery 1.4.2, the delegate and undelegate options are introduced instead of live, because they provide better context support // For example, for table, you used to use //. live () $ ("table "). each (function () {$ ("td", this ). live ("hover", function () {$ (this ). toggleClass ("hover") ;}); // $ ("table") is used now "). 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: $ (this ). offset (). top}, 500);} // then scroll to the class/area you want to go. $ ('. Area_name'). autoscroll ();
20. How to detect various browsers
If ($. browser. safari) // detect Safariif ($. browser. msie & $. browser. version> 6) // checks IE6 and later versions if ($. browser. msie & $. browser. version <= 6) // checks IE6 and earlier versions if ($. browser. mozilla & $. browser. version> = '1. 8 ') // detects FireFox 2 and later versions
21. How to replace words in a string
var el = $(‘#id'); el.html(el.html().replace(/word/ig, ”));
22. How to disable context menu
$(document).bind(‘contextmenu', 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 // if it contains returns true if the current element is not included. // returns false if the current element is not included }; // custom selector usage: $ ('. someClasses: test '). doSomething ();
24. How to check whether an element exists
If ($ ('# someDiv'). length) {// your sister, finally found}
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 how to retain a value in the text input field when the user does not enter a value $ (". 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 the setTimeout (function () {$ ('. mydiv '). hide ('blind', {}, 500)}, 5000); // while this is in 1.4, you can use delay () implementation of this function (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") {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 (1, 500 );
30. How to create a basic test for a function
// Separate the test into the module Module ("module B"); test ("some other test", function () {// specify the number of assertEquals (2) that are expected to run in the test; // A comparison asserted, equivalent to assertEquals (true, false, "failing test") of JUnit "); equals (true, true, "passing test ");});
31. How to get an element in jQuery
var cloned = $(‘#somediv').clone();
32. How to test whether an element is visible in jQuery?
If ($ (element). is (': visable') {// 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: $ (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 () {partition (this).html((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(this).target = "_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, // The 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 author $ (xml ). find ("Tutorial "). each (function () {$ ("# output "). append ($ (this ). attr ("author") + "");});}
46. How to check whether the image has been fully loaded
$('#theImage').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 the namespace $ ('input '). bind ('blur. validation ', function (e ){//...}); // The data method also accepts 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) {// cookie not 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 () {publish (this).html (). replace (regexp, '<a href = "$1" >1 1 </a>');}); return $ (this );} // usage $ ('P '). replaceUrl ();
The above content introduces you to the code snippets (50) of JQuery common examples for web Front-end development.