Summary of JQuery code collected over the years

Source: Internet
Author: User

1. How to Create nested Filters Copy codeThe Code is as follows: // you can 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 searchCopy codeThe Code is as follows: 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
// Match the <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 elementCopy codeThe Code is as follows: // 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

Copy codeThe Code is as follows: // 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)Copy codeThe Code is as follows: // 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>
<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 ToggleClassCopy codeThe Code is as follows: // 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 IECopy codeThe Code is as follows: if ($. browser. msie ){
// Internet Explorer is not that easy to use
}

8. How to Use jQuery to replace an elementCopy codeThe Code is as follows: $ ('# thatdiv'). replaceWith ('fnuh ');

9. How to verify whether an element is null

Copy codeThe Code is as follows: if ((('{keks'}.html (). trim ()){
// Nothing is found;
}

10. How to Find the index number of an element from an unsorted setCopy codeThe Code is as follows: $ ("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 elementsCopy codeCode: var e = $ ("", {href: "#", class: "a-class another-class", title :"..."});

14. How to use multiple attributes for filteringCopy codeThe Code is as follows: // 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 ++ ){
$ ("}
}; // Usage .preloadimages('image1.gif ','/path/to/image2.png ', 'some/image3.jpg ');

16. How to Set Event Handlers for any element that matches the selectorCopy codeThe Code is as follows: $ ('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 ElementCopy codeThe Code is as follows: $ ('# someElement'). find ('option: selected ');

18. How to hide an element that contains a value textCopy codeThe Code is as follows: $ ("p. value: contains ('thetextvalue')"). hide ();

19. If it is automatically rolled to a certain area of the pageCopy codeThe Code is as follows: 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 browsersCopy codeThe Code is as follows: if ($. browser. safari) // detects Safari
If ($. 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') // Checks FireFox 2 and later versions.

21. How to replace words in a stringCopy codeThe Code is as follows: var el = $ ('# id'); el.html(el.html (). replace (/word/ig ,''));

22. How to disable context menuCopy codeThe Code is as follows: $ (document). bind ('textmenu ', function (e ){
Return false;
});

23. How to define a custom SelectorCopy codeThe Code is as follows: $. 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. 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-clickCopy codeThe Code is as follows: $ ("# 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 fieldCopy codeThe Code is as follows: // This Code shows that when the user does not enter a value,
// How to retain data in text input fields
// A default 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)Copy codeThe Code is as follows: // This is the method we use 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 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 FieldCopy codeThe Code is as follows: 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 (500 );

30. How to create a basic test for a functionCopy codeThe Code is as follows: // put the test separately in the module.
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. How to get an element in jQuery

Var cloned = $ ('# somediv'). clone ();

32. How to test whether an element is visible in jQuery?Copy codeThe Code is as follows: if ($ (element). is (': visible ')){
// This element is visible.
}

33. How to place an element in the center of the screenCopy codeThe Code is as follows: 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 arrayCopy codeThe Code is as follows: var arrInputValues = new Array ();
$ ("Input [name = 'table [] ']"). each (function (){
ArrInputValues. push ($ (this). val ());
});

35. How to remove HTML from elementsCopy codeThe Code is as follows: (function ($ ){
$. Fn. stripHtml = function (){
Var regexp =/<("[^"] * "| '[^'] * '| [^'">]) *>/gi;
This. each (function (){
Certificate (this).html((this).html (). replace (regexp ,""));
});
Return $ (this );
}
}) (JQuery); // usage: $ ('P'). stripHtml ();

36. How to Use closest to obtain the parent ElementCopy codeThe Code is as follows: $ ('# searchbox'). closest ('div ');

37. How to Use Firebug and Firefox to record jQuery Event LogsCopy codeThe Code is as follows: // allow 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 windowCopy codeThe Code is as follows: 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 tabCopy codeThe Code is as follows: 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 ElementsCopy codeThe Code is as follows: // 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 pageCopy codeThe Code is as follows: 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 textCopy codeThe Code is as follows: // 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 yCopy codeThe Code is as follows: $ (document). ready (function (){
$ (Document). mousemove (function (e ){
Certificate ('{xy'{.html ("X Axis:" + e. pageX + "| Y Axis" + e. pageY );
});
});

44. How to change the entire List Element (LI) to clickableCopy codeThe Code is as follows: $ ("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)Copy codeThe Code is as follows: 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 loadedCopy codeThe Code is as follows: $ ('# theimag'). attr ('src', 'image.jpg'). load (function (){
Alert ('this Image Has Been loaded ');
});

47. How to Use jQuery to specify a namespace for an eventCopy codeThe Code is as follows: // You can bind a namespace to an event like this:
$ ('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 enabledCopy codeThe Code is as follows: 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 expireCopy codeThe Code is as follows: 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 ();

Finally, typographical layout is also a kind of physical activity. Resources are organized from the network and sent to those children's shoes that have not been sent to Tibet. If you have already collected these shoes, please do not throw bricks.

(Thanks for your feedback. The error has been corrected and we hope it will not mislead you)
PS: due to incorrect correction, the layout is out of order and is now released again.

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.