These years, my collection of jquery code summary _jquery

Source: Internet
Author: User
1. How to create a nested filter
Copy Code code as follows:

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,
Query removed any (: not) (: has)
Contains child nodes with Class "Selected" (. selected).
. Filter (": Not (: Has (. selected))")

2. How to reuse element search
Copy Code code 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 Keep list based on a 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
Copy Code code as follows:

The JQuery 1.4.* contains support for this has approach. This method finds
Does an element contain another element class or any other
What you are looking for and what to do on top of it.
$ ("input"). has (". Email"). AddClass ("Email_icon");

4. How to use jquery to switch style sheets

Copy Code code as follows:

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


5. How to limit selection (based on optimization purposes)
Copy Code code as follows:

Use the label name to prefix the class name whenever possible,
So jquery doesn't need to spend more time searching.
The elements you want. And one thing to keep in mind is that
The more specific the manipulation of the elements on your page,
The more you can reduce 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 use Toggleclass correctly
Copy Code code as follows:

The Toggle (toggle) class allows you to base a class on the
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 easily do this
A.toggleclass (' BlueButton ');


7. How to set the features of IE specific
Copy Code code as follows:

if ($.browser.msie) {
Internet Explorer is actually not that useful
}

8. How to use jquery to replace an element
Copy Code code as follows:

$ (' #thatdiv '). ReplaceWith (' Fnuh ');

9. How to verify that an element is empty

Copy Code code as follows:

if ($ (' #keks '). html (). Trim ()) {
Nothing has been found;
}


10. How to find the index number of an element from an unordered collection
Copy Code code 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 object literals (literal) to define attributes when creating elements
Copy Code code as follows:

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

14. How to use multiple properties to filter
Copy Code code as follows:

When many similar input elements with different types are used,
This method based on accuracy is useful for var elements = $ (' #someid Input[type=sometype][value=somevalue] '). get (); 15. How to use jquery to preload an image

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 an event handler for any element that matches the selector
Copy Code code as follows:

$ (' Button.someclass '). Live (' click ', someFunction);
Note that in the jquery 1.4.2, the delegate and Undelegate options
are introduced instead of live because they provide better contextual support
For example, in the case of table, you used
. Live ()
$ ("table"). each (function () {
$ ("TD", this). Live ("hover", function () {
$ (this). Toggleclass ("hover");
});
});
Now use
$ ("table"). Delegate ("TD", "hover", function () {
$ (this). Toggleclass ("hover");
});

17. How to find an option element that has been selected
Copy Code code as follows:

$ (' #someElement '). Find (' option:selected ');

18. How to hide an element that contains a text of a value
Copy Code code as follows:

$ ("P.value:contains (' Thetextvalue ')"). Hide ();

19. If you scroll to an area of the page automatically
Copy Code code as follows:

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

20. How to detect various browsers
Copy Code code as follows:

if ($.browser.safari)//Detect Safari
if ($.browser.msie && $.browser.version > 6)//Detect IE6 and later versions
if ($.browser.msie && $.browser.version <= 6)//Detect IE6 and previous versions
if ($.browser.mozilla && $.browser.version >= ' 1.8 ')//Check Firefox 2 and after version

21. How to replace the words in a string
Copy Code code as follows:

var el = $ (' #id '); El.html (el.html (). Replace (/word/ig, '));

22. How to disable right-click context menu
Copy Code code as follows:

$ (document). Bind (' ContextMenu ', function (e) {
return false;
});

23. How to define a custom selector
Copy Code code as follows:

$.expr[': '].mycustomselector = function (element, index, meta, stack) {
Element-a DOM element
Current looping index in the index– stack
meta– the metadata about the selector
stack– the stack of all elements to loop
Returns true if the current element is included
Returns False if it does not contain the current element;
Custom Selector Usage:
$ ('. Someclasses:test '). dosomething (); 24. How to check if an element exists
if ($ (' #someDiv '). Length) {
Your sister, finally found.
}

25. How to use jquery to detect two mouse clicks with right and left buttons
Copy Code code 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
Copy Code code as follows:

This code shows that when the user does not enter a value,
How to preserve in the input field of a text type
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 close elements after a period of time (support version 1.4)
Copy Code code as follows:

This is the way we use settimeout to implement in 1.3.2.
settimeout (function () {
$ ('. Mydiv '). Hide (' blind ', {}, 500)
}, 5000);
And this is the way you can use the delay () function in 1.4 (it's like hibernation)
$ (". Mydiv"). Delay (5000). Hide (' blind ', {}, 500); 28. How to dynamically add elements that have been created to the DOM
var newdiv = $ (');
NEWDIV.ATTR (' id ', ' mynewdiv '). Appendto (' body ');

29. How to limit the number of characters in the "Text-area" field
Copy Code code 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 > | | keycode = | | 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
Copy Code code as follows:

Put the test in the module alone
Module ("Module B");
Test ("Some other test", function () {
Indicates how many assertions are expected to run within the test
Expect (2);
A comparison assertion, equivalent to JUnit's assertequals
Equals (True, false, "failing test");
Equals (True, true, "passing Test");
}); 31. How to clone an element in jquery

var cloned = $ (' #somediv '). Clone ();

32. How to test whether an element is visible in jquery
Copy Code code as follows:

if ($ (Element). Is (': Visible ')) {
The element is visible
}

33. How to place an element in the center of the screen
Copy Code code 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;
}//This uses the above function: $ (Element). Center ();

34. How to put the values of all elements that have a particular name in an array
Copy Code code as follows:

var arrinputvalues = new Array ();
$ ("Input[name= ' table[]"). each (function () {
Arrinputvalues.push ($ (this). Val ());
});

35. How to remove HTML from an element
Copy Code code as follows:

(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
Copy Code code as follows:
$ (' #searchBox '). Closest (' div ');

37. How to use Firebug and Firefox to record jquery event logs
Copy Code code as follows:

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

38. How to force a link to open in a pop-up window
Copy Code code 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 a link to open in a new tab
Copy Code code as follows:

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 sibling elements
Copy Code code as follows:

Don't do that
$ (' #nav li '). Click (function () {
$ (' #nav Li '). Removeclass (' active ');
$ (this). addclass (' active ');
}); Alternative approach is

$ (' #nav li '). Click (function () {
$ (this). addclass (' active '). Siblings (). Removeclass (' active ');
});

41. How to toggle all check boxes on the page
Copy Code code as follows:

var tog = false;
Or True if they are selected when they are loaded

$ (' a '). Click (function () {
$ ("Input[type=checkbox]"). attr ("Checked",!tog);
Tog =!tog;
});

42. How to filter a list of elements based on some input text
Copy Code code as follows:

If the value of the element matches the input text
The element will be returned $ ('. SomeClass '). Filter (function () {
return $ (this). attr (' value ') = = $ (' Input#someid '). Val ();
})

43. How to get mouse pad cursor position x and Y
Copy Code code as follows:

$ (document). Ready (function () {
$ (document). MouseMove (function (e) {
$ (' #XY '). HTML ("X Axis:" + E.pagex + "| Y Axis "+ e.pagey);
});
});

44. How to turn the entire list element (Element,li) into a clickable
Copy Code code 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 Code code as follows:

function Parsexml (XML) {
Find each tutorial and print out author
$ (XML). Find ("Tutorial"). each (function () {
$ ("#output"). Append ($ (this). attr ("author") + "");
});
}

46. How to check if the image has been fully loaded in
Copy Code code as follows:

$ (' #theImage '). attr (' src ', ' image.jpg '). Load (function () {
Alert (' This Image has Been Loaded ');
});

47. How to use jquery to specify namespaces for events
Copy Code code as follows:

Events can bind namespaces like this
$ (' input '). Bind (' Blur.validation ', function (e) {
// ...
});

The data method also accepts namespaces
$ (' input '). Data (' Validation.isvalid ', true);

48. How to check whether cookies are enabled
Copy Code code 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) {
Cookies are not enabled
}

49. How to make cookies expire
Copy Code code as follows:

var date = new Date ();
Date.settime (Date.gettime () + (x * 60 * 1000));
$.cookie (' Example ', ' foo ', {expires:date}); 50. How to replace any URL in the page with a clickable link

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

Finally finished, typesetting is also a manual work. Resources from the network, to those who did not send hidden shoes, if you have already collected, please do not throw bricks.

(Thank you for your feedback, the wrong place has been corrected, I hope not to mislead you)
PS: Due to correction errors, resulting in typographical confusion, now republish.

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.