30 classic jquery Code Development tips _jquery

Source: Internet
Author: User
Tags tag name

The examples in this article summarize the 30 classic jquery code development techniques. Share to everyone for your reference. Specifically as follows:

1. Creating a nested filter

Copy Code code as follows:
. Filter (": Not (: Has (. selected)")//Remove all elements that do not contain class. Selected

2. Reuse your element query

Copy Code code as follows:
var AllItems = $ ("Div.item");
var keeplist = $ ("Div#container1 Div.item");
<div>class names: $ (formtolookat + "input:checked"). each (function () {keeplistkeeplist = Keeplist.filter ("." + $ (t His). attr ("name"));
});
</div>

3. Use has () to determine whether an element contains a specific class or element

Copy Code code as follows:
JQuery 1.4.* includes support for the has method. This method would find
If a element contains a certain other element class or whatever it is
You are are looking for and do anything your want to them.
$ ("input"). has (". Email"). AddClass ("Email_icon");

4. Use jquery to toggle Styles

Copy Code code as follows:
Look for the Media-type your wish to switch then set the href to your new style sheet
$ (' link[media= ' screen ']. attr (' href ', ' alternative.css ');

5. Restricted areas of choice

Copy Code code as follows:
Where possible, pre-fix your class names with a tag name
So this jQuery doesn ' t have to spend more time searching
For the element "re after." Also Remember that anything
You can does more specific about where the element is
On your page would cut down on the Execution/search times
var In_stock = $ (' #shopping_cart_items input.is_in_stock ');
<ul id= "Shopping_cart_items" >
<li> <input value= "item-x" name= "Item" type= "Radio" > Item x</li>
<li> <input value= "item-y" name= "Item" type= "Radio" > Item y</li>
<li> <input value= "item-z" name= "Item" type= "Radio" > Item z</li>
</ul>

6. How to use Toggleclass correctly

Copy Code code as follows:
Toggle class allows you to add or remove a class
From a element depending on the presence of
Class. Where some developers would use:
A.hasclass (' BlueButton ')? A.removeclass (' BlueButton '): A.addclass (' BlueButton ');
Toggleclass allows to easily doing this usinga.toggleclass (' BlueButton ');

7. Set the function specified by IE

Copy Code code as follows:
if ($.browser.msie) {
Internet Explorer is a sadist.
}

8. Use jquery to replace an element

Copy Code code as follows:
$ (' #thatdiv '). ReplaceWith (' Fnuh ');

9. Verify that an element is empty

Copy Code code as follows:
if ($ (' #keks '). HTML ()) {
Nothing found;
}

10. Find an index of an element in a unordered set

Copy Code code as follows:
$ ("ul > Li"). Click (function () {var index = $ (this). Prevall (). length;});

11. Bind a function to an event

Copy Code code as follows:
$ (' #foo '). Bind (' click ', function () {alert (' User clicked on ' foo. "');});

12. Add HTML to an element

Copy Code code as follows:
$ (' #lal '). Append (' Sometext ');

13. Use objects to define attributes when creating elements

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

14. Filter multiple properties using filters

Copy Code code as follows:
This precision-based approached can is useful when to use
Lots of similar input elements which have different types
var elements = $ (' #someid Input[type=sometype][value=somevalue] '). get ();

15. Pre-loading pictures with jquery

Copy Code code as follows:
Jquery.preloadimages = function () {for (var i = 0; I '). attr (' src ', arguments[i]);};
Usage $.preloadimages (' image1.gif ', '/path/to/image2.png ', ' some/image3.jpg ');

16. Set any event handlers that match a selector
[code]$ (' Button.someclass '). Live (' click ', someFunction);
Note This in JQuery 1.4.2, the delegate and undelegate options have been
Introduced to replace live as they offer better support for context
For example, in terms of a table where before your would use.
//
. Live () $ ("table"). each (function () {$ (' TD ', this '). Live ("hover", function () {$ (this). Toggleclass ("hover");});
Now use.
$ ("table"). Delegate ("TD", "hover", function () {$ (this). Toggleclass ("hover");

17. Find the selected OPTION element

Copy Code code as follows:
$ (' #someElement '). Find (' option:selected ');

18. Hide elements that contain specific values

Copy Code code as follows:
$ ("P.value:contains (' Thetextvalue ')"). Hide ();

19. Automatic scrolling to specific areas of the page

Copy Code code as follows:
JQuery.fn.autoscroll = function (selector) {$ (' html,body '). Animate ({scrolltop: $ (selector). Offset (). Top}, 500);}
Then to scroll to the Class/area your wish to get to like this:
$ ('. Area_name '). AutoScroll ();

20. Detect various Browsers

Copy Code code as follows:
Detect Safari (if ($.browser.safari)), detect IE6 and over (if ($.browser.msie && $.browser.version > 6)), Det ECT IE6 and below (if ($.browser.msie && $.browser.version <= 6)), detect FireFox 2 and above (if ($.browser.m Ozilla && $.browser.version >= ' 1.8 ')

21. Replace the word in the string

Copy Code code as follows:
var el = $ (' #id '); El.html (el.html (). Replace (/word/ig, '));

22. Close the right button menu

Copy Code code as follows:
$ (document). Bind (' ContextMenu ', function (e) {return false;});

23. Define a custom Selector

Copy Code code as follows:
$.expr[': '].mycustomselector = function (element, index, meta, stack) {
Element-is a DOM element
Index-the current loop index in stack
Meta-meta data about your selector
Stack-stack of all elements to loop
Return true to include the current element
return false to Explude current element
};
Custom Selector Usage:
$ ('. Someclasses:test '). dosomething ();

24. Determine if an element exists

Copy Code code as follows:
if ($ (' #someDiv '). Length) {
Hooray!!! It exists ...
}

25. Use jquery to determine the mouse key click

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. Show or delete the default value of the input box

Copy Code code as follows:
This snippet'll show your How to keep a default value
In a text input field for when a user hasn ' t entered in
A value to replace it
Swap_val = [];
$ (". Swap"). each (function (i) {swap_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]);}}); <input value= "Enter Username here ..." type=text>

27. Automatically hide or close elements after a specified time (1.4 support)

Copy Code code as follows:
Here's how we used the IT in 1.3.2 using settimeout
settimeout (function () {$ ('. Mydiv '). Hide (' blind ', {}, 500)}, 5000);
And here's how can I do it with 1.4 using the delay () feature (this is a lot like sleep)
$ (". Mydiv"). Delay (5000). Hide (' blind ', {}, 500);

28. Dynamically creating elements to DOM

Copy Code code as follows:
var newgbin1div = $ (');
NEWGBIN1DIV.ATTR (' id ', ' gbin1.com '). Appendto (' body ');

29. Limit the number of characters textarea

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") {
//apply the standard 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 > A | | keycode = | | keycode = 0 | | keycode = +) &&am p;!ob.ctrlkey &&!ob.altkey &&!hasselection); };
This.onkeyup = function () {if (This.value.length > Max) {this.value = this.value.substring (0,max);}} }); };
//usage:
$ (' #gbin1textarea '). MaxLength;

30. Create a basic test case for a function

Copy Code code as follows:
Separate tests into modules.
Module ("Module B");
Test ("Some other gbin1.com test", function () {
Specify how many assertions are expected to run within a test. Expect (2); A comparison assertion, equivalent to JUnit ' s assertequals.
Equals (True, false, "failing test");
Equals (True, true, "passing Test");
});

I hope this article will help you with your jquery programming.

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.