jquery Code Classic Fragment

Source: Internet
Author: User

jquery Code Classic Fragment

1. How to modify jquery default encoding (e.g. default UTF-8 to change 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" >   

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

3. JQuery Determines whether the event is bound on the element//jquery event encapsulation supports determining whether an event is bound on an element,

This method applies only to jquery-bound events

   var $events = $ ("#foo"). Data ("Events");     if ($events && $events ["click"]) {      //     }

4. How to use jquery to switch style sheets//Find out the 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 (for optimization purposes):

Use the tag name as a prefix to the class name whenever possible.

So jquery doesn't have to spend more time searching for

The element you want. Another thing to keep in mind is that

The more specific the manipulation of the elements on your page,

The more time you can reduce execution 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> <li><input type= "Radio" value= "item-y" name= "item" class= "3-5_days"/> Item y</li&   Gt <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 base a class

Whether it exists to add or remove the class.

In this case some developers use: A.hasclass (' BlueButton ')? A.removeclass (' BlueButton '): A.addclass (' BlueButton ');

Toggleclass allows you to use the following statement to make it easy to do this a.toggleclass (' BlueButton ');

7. How to set the features specific to IE:

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

8. How to use jquery instead of an element: $ (' #thatdiv '). ReplaceWith (' Fnuh ');

9. How to verify that an element is empty:

// Method One if (! $ (' #keks '// nothing found; }//  method Two if ($ (' #keks '). Is (": Empty"//}

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

$ ("ul > Li"). Click (function () { var index = $ (this///prevall ([expr]): Find the current element All previous peer elements});

11. How to bind a function to an event:

// method One $ (' #foo '). Click (function(event) {alert (' User clicked on ' foo. ") ); }); // method Two, support for dynamic parameter transfer function (Event) {alert (' User clicked on ' foo. "' + Event.data.test1 + event.data.test2);});

12. How to append or add HTML to the element: $ (' #lal '). Append (' Sometext ');

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

var e = $ ("", {href: "#", Class: "A-class Another-class", Title: "..."});

14. How to use multiple properties to filter//when using many similar input elements with different types,

This precision-based approach is useful

var elements = $ (' #someid Input[type=sometype][value=somevalue] '). get ();

15. How to preload an image using jquery:

function () {  for (var i = 0; i < arguments.length; i++) {$ ("// usage $.preloadimages (' image1.gif ', '/path/to/image2.png ', ' some/image3.jpg ');

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

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


17. How to find an option element that has been selected: $ (' #someElement '). Find (' option:selected ');

18. How to hide an element that contains a value text: $ ("P.value:contains (' Thetextvalue ')"). Hide ();

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 are left. In this case, the// query removes any (: not) with a child node (: has)// containing the class "Selected" (. selected) . Filter (": Not (: Have (. selected))")


20. How to detect various browsers:

Detects Safari (if ($.browser.safari)), detects IE6 and later versions (if ($.browser.msie && $.browser.version > 6)), detects IE6 and previous versions (if ($.browser.msie && $.browser.version <= 6)) to detect Firefox 2 and later (if ($.browser.mozilla && $.browser.ver Sion >= ' 1.8 ')) 21. Any use has () to check whether an element contains a class or an element://jquery 1.4.* contains support for this has method. This method finds out whether an element contains another element class or anything else that you are looking for and that you want to manipulate on top of it. $ ("input"). has (". Email"). AddClass ("Email_icon");

22. How to disable the 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-a DOM element//index– stack when Front loop index//meta– metadata about the selector//stack– the stack of all elements to loop//returns True if the current element is contained//returns FALSE if the current element is not included; Custom Selector Usage: $ ('. Someclasses:test '). dosomething ();

24. How to check if an element exists if ($ (' #someDiv '). Length) {//hooray!!! It 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) {alert ("Right Mouse button Clicked"); } });

26. How to replace the words in the string var el = $ (' #id '); El.html (el.html (). Replace (/word/ig, "));

27. How to automatically hide or close an element after a period of time (1.4 versions supported)://This is the way we use SetTimeout in 1.3.2 setTimeout (function () {$ ('. Mydiv '). Hide (' blind ', {} , 500)}, 5000); And this is the way in which the delay () function can be implemented in 1.4 (which is much like hibernation) $ (". Mydiv"). Delay ("."). Hide (' blind ', {}, 500);

28. How to dynamically add the created elements to the DOM: var newdiv = $ (' <div></div> '); NEWDIV.ATTR (' id ', ' mynewdiv '). AppendTo (' body ');

29. How to limit the number of characters in the "Text-area" field: JQuery.fn.maxLength = function (max) {    return 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 > | | keycode = = | | keycode = 0 | | keycode = +) &&!ob . Ctrlkey &&!ob.altkey &&!hasselection);            };             this.onkeyup = function () {                 if (This.value.length > Max) {                     This.value = this.value.substring (0,max);                }             };        }    }); }; Use $ (' #mytextarea '). MaxLength (500);

30. How jquery registers and disables jquery global event//jquery Register AJAX global Event Ajaxstart,ajaxstop: $ (document). Ajaxstart (function () {$ ("#background , #progressBar "). Show (); }). Ajaxstop (function () {$ ("#background, #progressBar"). Hide ();}); The AJAX request disables the global event: $.ajax () has a parameter global (default: TRUE) to trigger global AJAX events. Setting to False will not trigger global AJAX events, such as Ajaxstart or ajaxstop, which can be used to control different Aja X event.

31. How to clone an element in jquery: var cloned = $ (' #somediv '). Clone ();

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

if (Element). Is (': visible ') {//the element is visible}

33. How to place an element in the center of the screen: JQuery.fn.center = function () {return This.each (function () {$ (this). css ({position: ' AB Solute ', Top, ($ (window). Height ()-this.height ())/2 + $ (window). scrolltop () + ' px ', left, ($ (window). wid   Th ()-this.width ())/2 + $ (window). ScrollLeft () + ' px '}); }); }//This uses the above function: $ (Element). Center (); 34. How to put the values of all elements with a particular name in an array: var arrinputvalues = new Array (); $ ("input[name= ' xxx ']"). each (function () {Arrinputvalues.push ($ (this). Val ());});

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: $ (' P '). striphtml ();

36. How to use closest to get the parent element: $ (' #searchBox '). Closest (' div ');

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

Allow chained logging jQuery.log = JQuery.fn.log = function (msg) {if (console) {Console.log ("%s:%o", MSG, this); } return this; }; Usage: $ (' #someDiv '). Hide (). log (' div hidden '). addclass (' SomeClass ');

38. How to force open the link in the pop-up window: $ (' A.popup '). Live (' click ', function () {var NewWindow = window.open ($ (this). attr (' href '), ', '   Height=200,width=150 ');   if (window.focus) {newwindow.focus (); } return false; });

39. How to force a link to open in a new tab: $ (' A.newtab '). Live (' click ', function () {var newwindow=window.open (this.href);   $ (this). target = "_blank"; return false; });

40. How to use. Siblings () in jquery to select sibling elements//Do not do this $ (' #nav li '). Click (function () {$ (' #nav Li '). Removeclass (' active '); $ (this). addclass (' active '); }); The alternative approach is $ (' #nav li '). Click (function () {$ (this). addclass (' active '). Siblings (). Removeclass (' active ');});

41. How to toggle all check boxes on the page: var tog = false;   Or True if they are selected at load time $ (' a '). Click (function () {$ ("Input[type=checkbox]"). attr ("Checked",!tog); Tog =!tog; });

42. How to filter a list of elements based on some input text://The element will be returned $ ('. SomeClass ') If the value of the element matches the input text. Filter (function () {return $ (this). attr (' value ') ) = = $ (' Input#someid '). Val (); })

43. How to get the mouse pad cursor position X and y $ (document). Ready (function () {$ (document). MouseMove (function (e) {$ (' #XY '). HTML ("X Axis:" + E.P Agex + "|   Y Axis "+ e.pagey); }); });

44. How to extend the String object's method $.extend (String.prototype, {        Ispositiveinteger: function () {            return (new RegExp (/^[1-9]\d*$/). Test (this));        },         isinteger:function () {             return (new RegExp (/^\d+$/). Test (this));        },         isnumber:function (value, Element) {            return (new RegExp (/^-) (?: \ d+|\d{1,3} (?:, \d{3}) +) (?: \. \d+) $/). Test (this));        },         trim:function () {             return This.replace (/(^\s*) | ( \s*$) |\r|\n/g, "");        }, &NBSP;&NBsp;      trans:function () {             Return This.replace (/&lt;/g, ' < '). Replace (/&gt;/g, ' > '). replace (/&quot;/g, ' "');        },         replaceall:function (OS, NS) {            return this.replace (New RegExp (OS, "GM"), NS );        },         skipchar:function (CH) {             if (!this | | this.length===0) {return ';}  & nbsp;          if (This.charat (0) ===ch) {return this.substring (1). Skipchar (CH);}             return this;        },         isvalidpwd:function () {&Nbsp;           return (New RegExp (/^ ([_]|[ A-za-z0-9]) {6,32}$/). Test (this));        },         isvalidmail:function () {             return (New RegExp (/^\w+ (-\w+) | ( \.\w+)) *\@[a-za-z0-9]+ ((\.| -) [a-za-z0-9]+] *\. [a-za-z0-9]+$/). Test (This.trim ()));        },         isspaces:function () {             for (var i=0; i<this.length; i+=1) {                 var ch = this.charat (i);                 if (ch!= ' && Ch!= "\ n" && ch!= "\ T" && ch!= "\ r") {return false;}             }            return true;        },         isphone:function () {             return (New RegExp (/(^ ([0-9]{3,4}[-]) \d{3,8} ( -\d{1,6})? $) | (^\ ([0-9]{3,4}\) \d{3,8} (\ (\d{1,6}\))? $) | (^\d{3,8}$)/). Test (this));        },         isurl:function () {             return (New RegExp (/^[a-za-z]+:\/\/([a-za-z0-9\-\.] +) ([-\w. \/?%&=:]*) $/). Test (this));        },         isexternalurl:function () {            return This.isurl () && this.indexof (" ://"+document.domain) = =-1;        }    });

45. How to Standardize write jquery plugins:

(function ($) {$.fn.extend ({pluginone:function () {) {return This.each (function () {//         My Code});         }, Plugintwo:function () {return This.each (function () {//My Code}); }     }); }) (JQuery);

46. How to check if the image has been fully loaded in $ (' #theImage '). attr (' src ', ' image.jpg '). Load (function () {alert (' This image has Been Loaded ');});

47. How to use jquery to specify namespaces for events://Events can bind namespaces $ (' input ') in this way. Bind (' Blur.validation ', function (e) {//...}); The data method also accepts the namespace $ (' input '). Data (' Validation.isvalid ', true);

48. How to check if the cookie is 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 cookies are enabled}

49. How to expire a cookie: var date = new Date (); Date.settime (Date.gettime () + (x * 60 * 1000)); $.cookie (' Example ', ' foo ', {expires:date});

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;     Return This.each (function () {$ (this). HTML ($ (this). html (). Replace (RegExp, ' <a href= ' >$1</a> ')   ); }); }//Use $ (' 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.