JQuery code summary collected over the years _ jquery-js tutorials

Source: Internet
Author: User
Typographical layout is also a kind of physical activity. Resources are organized from the network and sent to those children's shoes that haven't been sent to Tibet. If you have already collected the resources, please do not throw bricks. 1. How to Create nested filters?

The Code is as follows:


// 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

The Code is as follows:


Var allItems = $ ("p. item ");
Var keepList = $ ("p # container1 p. 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
// Class names:
$ (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 element

The 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

The 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)

The 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 ');


  • Item X

  • Item Y

  • Item Z



6. How to correctly use ToggleClass

The 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 IE

The Code is as follows:


If ($. browser. msie ){
// Internet Explorer is not that easy to use
}


8. How to Use jQuery to replace an element

The Code is as follows:


$ ('# Thatp'). replaceWith ('fnuh ');


9. How to verify whether an element is null

The Code is as follows:


If ((('{keks'}.html (). trim ()){
// Nothing is found;
}



10. How to Find the index number of an element from an unsorted set

The 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 elements

The Code is as follows:


Var e = $ ("", {href: "#", class: "a-class another-class", title :"..."});


14. How to use multiple attributes for filtering

The 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 ++ ){
$ (""). Attr ('src', arguments [I]);
}
}; // Usage .preloadimages('image1.gif ','/path/to/image2.png ', 'some/image3.jpg ');


16. How to Set Event Handlers for any element that matches the selector

The 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 Element

The Code is as follows:


$ ('# SomeElement'). find ('option: selected ');


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

The Code is as follows:


$ ("P. value: contains ('thetextvalue')"). hide ();


19. If it is automatically rolled to a certain area of the page

The 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 browsers

The 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 string

The Code is as follows:


Var el = $ ('# id'); el.html(el.html (). replace (/word/ig ,''));


22. How to disable context menu

The Code is as follows:


$ (Document). bind ('textmenu ', function (e ){
Return false;
});


23. How to define a custom Selector

The 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-click

The 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 field

The 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)

The Code is as follows:


// This is implemented using setTimeout in 1.3.2.
SetTimeout (function (){
$ ('. Myp'). hide ('blind', {}, 500)
},5000 );
// This method can be implemented using the delay () function in 1.4 (this is like sleep)
$ (". Myp"). 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 Field

The 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 function

The Code is as follows:


// 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. How to get an element in jQuery

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


32. How to test whether an element is visible in jQuery?

The Code is as follows:


If ($ (element). is (': visible ')){
// This element is visible.
}


33. How to place an element in the center of the screen

The 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 array

The Code is as follows:


Var arrInputValues = new Array ();
$ ("Input [name = 'table [] ']"). each (function (){
ArrInputValues. push ($ (this). val ());
});


35. How to remove HTML from elements

The 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 Element

The Code is as follows:

$ ('# Searchbox'). closest ('P ');


37. How to Use Firebug and Firefox to record jQuery Event Logs

The Code is as follows:


// Enable chained Logging
// Usage:
$ ('# Somediv'). hide (). log ('P 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

The 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 tab

The 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 Elements

The 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 page

The 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 text

The 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 y

The 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 clickable

The Code is as follows:


$ ("Ul li"). click (function (){
Window. location = $ (this). find ("a"). attr ("href ");
Return false;
});


  • Link 1

  • Link 2

  • Link 3

  • Link 4



45. How to Use jQuery to parse XML (basic example)

The 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 loaded

The 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 event

The Code is as follows:


// 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

The 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 expire

The 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 (
Certificate (this).html (). replace (regexp, '$1 ')
);
});
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.