50 Common jquery Codes

Source: Internet
Author: User
Tags tag name

1. 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 are left. In this case, the  //query removes any (: not) with a child node (: Has)  //containing the class "Selected" (. 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,  //Based on a check box to crop "Keep list", check box name  //conform to <div>class names:x$ (Formtolookat + "input:checked"). each ( function () {      keeplist = Keeplist.filter ("." + $ (This). attr ("name"));  });  

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

The JQuery 1.4.* contains support for this has method. This method finds out  whether or not an element contains another element class or anything else that  you are looking for and that you want to manipulate on top of it.  

4. How to use jquery to switch style sheets

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

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

Use the tag name as much as possible to prefix the class name,//  so that jquery does not need to spend more time searching for  //The elements you want. One more thing to keep in mind is that the  more specific the manipulation of the elements on your page, the  more you can reduce the time it takes to execute and search.  

6. How to use Toggleclass correctly

The Toggle (toggle) class allows you to add or delete 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  

7. How to set the features specific to IE

if ($.browser.msie) {///Internet Explorer is not really that useful  

8. How to use jquery instead of an element

9. How to verify that an element is empty

if ($ (' #keks '). HTML ()) {//nothing found;  

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

11. How to bind a function to an event

12. How to append or add HTML to an 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 with different types,  //This precision-based approach is useful  

15. How to pre-load images using jquery

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

16. How to set event handlers for any element that matches a selector

$ (' Button.someclass '). Live (' click ', someFunction);//Note that in jquery 1.4.2, 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  //.live ()  $ ("table"). each (function () {$ ("TD", this). Live ("hover" , function () {     $ (this). Toggleclass ("hover");}); /Use Now  

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

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

19. If you scroll to an area of the page automatically

JQuery.fn.autoscroll = function (selector) {   $ (' html,body '). Animate (       {scrolltop: $ (selector). Offset (). Top},   ;  }  Then scroll like this to the class/area you want to go to.  $ ('. Area_name '). AutoScroll ();

20. How to detect various browsers

if ($.browser.safari)  //Detect Safariif ($.browser.msie && $.browser.version > 6)//Detect IE6 and later version if ($. Browser.msie && $.browser.version <= 6)  //Detect IE6 and previous versions if ($.browser.mozilla && $.browser.version >= ' 1.8 ')   

21. How to replace words in a string

var el = $ (' #id ');    

22. How to disable the right-click context menu

23. How to define a custom selector

$.expr[': '].mycustomselector = function (element, index, meta, stack) {   //element-The   current circular index in a DOM element//index– stack. c2/>//meta– metadata about the selector/   /stack– The stack of all the elements to loop   //If the current element is contained, returns true   //returns False if it does not contain the current element;   How to use custom selectors:   

24. How to check if an element exists

25. How to use jquery to detect both right and left mouse clicks

$ ("#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) {     

26. How to display or delete the default values in the input field

This code shows when the user does not enter a value,  //How to keep//a default value in the input field of the text type  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 close elements after a period of time (1.4 versions supported)

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

28. How to dynamically add elements that have been created to the DOM

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 > | | keycode = = | | keycode = 0 | | keycode = =)      & ;&!ob.ctrlkey &&!ob.altkey &&!hasselection); }; This.onkeyup = function () {  if (This.value.length > Max) {      this.value = this.value.substring (0, max);  } };     } });};/ /usage  

30. How to create a basic test for a function

Place the test separately in module  ("Module B"), Test ("Some other test", function () {//) indicate how many assertions inside the test are expected to run   expect (2);//A comparison assertion, Equivalent to JUnit's assertequals   

31. How to clone an element in jquery

32. How to test whether an element is visible in jquery

if (Element). Is (': visible ') = = ' true ') {//the 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 ()) c4/>/+$ (window). scrolltop () + ' px '); This.css (' Left ', ($ (window). Width ()-this.width ())        /2 + $ (window). ScrollLeft () + ' px '); This will use the above function:  

34. How to put the values of all elements with a particular name in an array

35. How to remove HTML from an element

(function ($) {$.fn.striphtml = function () {     var regexp =/< ("[^"]* "|" [^ ']* ' | [^ ' ";]) *>/gi;     This.each (function () {$ (this). HTML ($ (this). html (). Replace (RegExp, ""));     });     return $ (this); }}) (jQuery);//Usage:  

36. How to use closest to get the parent element

37. How to use Firebug and Firefox to record the jquery event log

Allow chained logging  //Usage:  $ (' #someDiv '). Hide (). log (' div hidden '). addclass (' SomeClass '); jQuery.log = JQuery.fn.log = Function (msg) {if (console) {     

38. How to force a link to open in a pop-up window

JQuery (' A.popup '). Live (' click ', Function () {NewWindow = window.open ($ (this). attr (' href '), ', ' height=200,width=150 ' ); if (Window.focus) {     

39. How to force a link to open in a new tab

40. How to use. Siblings () in jquery to select sibling elements

Do not do  $ (' #nav li '). Click (function () {$ (' #nav Li '). Removeclass (' active '); $ (this). addclass (' active ');}); /Alternative approach is  

41. How to toggle all the checkboxes on the page

var tog = false;//or True if they are selected at load time  

42. How to filter a list of elements based on some input text

If the value of the element matches the input text,  //The element is returned  

43. How to get the mouse pad cursor position x and Y

$ (document). Ready (function () {$ (document). MouseMove (function (e) {     

44. How to turn the entire list element (Element,li) into clickable

45. How to use jquery to parse XML (basic example)

function Parsexml (XML) {//finds each Tutorial and prints out author   $ (XML). Find ("Tutorial"). each (function () {     

46. How to check if the image has been fully loaded in

47. How to use jquery to specify namespaces for events

An event can bind namespace  $ (' input ') in this way. Bind (' Blur.validation ', function (e) {//...  }); The/data method also accepts namespaces  

48. How to check if cookies are enabled

var dt = new Date ();d t.setseconds (dt.getseconds () +);d Ocument.cookie = "cookietest=1; Expires= "+ dt.togmtstring (); var cookiesenabled = document.cookie.indexOf (" cookietest= ")! = -1;if (!cookiesenabled) {// Cookies are not enabled  

49. How to make cookies expire

50. How to use a clickable link to replace any URL in the page

$.fn.replaceurl = function () {var regexp =      /((FTP|HTTP|HTTPS): \/\/(\w+:{0,1}\w*@)? ( \s+) (: [0-9]+)? (\/|\/([\w#!:.? +=&%@!\-\/])?) /gi; This.each (function () {     $ (this). HTML ($ (this). html (). Replace (RegExp, ' <a href= ' ">$1</a> '));     }); return $ (this);} Usage  

 

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.