30 classic jQuery code development tips-jquery-js tutorial

Source: Internet
Author: User
This article mainly introduces 30 typical jQuery code development skills, including common attributes, methods, and elements, which are of great practical value, you can refer to the examples in this article to summarize 30 typical jQuery code development skills. Share it with you for your reference. The details are as follows:

1. Create a nested Filter

The Code is as follows:

. Filter (": not (: has (. selected)") // remove all elements that do not contain the. selected class.

2. reuse your element Query

The Code is as follows:

Var allItems = $ ("p. item ");
Var keepList = $ ("p # container1 p. item ");

Class names: $ (formToLookAt + "input: checked "). each (function () {keepListkeepList = keepList. filter (". "+ $ (this ). attr ("name "));
});

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

The Code is as follows:

// JQuery 1. 4. * supported des support for the has method. This method will find
// If a an element contains a certain other element class or whatever it is
// You are looking for and do anything you want to them.
$ ("Input"). has (". email"). addClass ("email_icon ");

4. Use jQuery to switch the style

The Code is as follows:

// Look for the media-type you wish to switch then set the href to your new style sheet
$ ('Link [media = 'screen'] '). attr ('href', 'Alternative.css ');

5. Restrict the selected region

The Code is as follows:

// Where possible, pre-fix your class names with a tag name
// So that jQuery doesn' t have to spend more time searching
// For the element you're after. Also remember that anything
// You can do to be more specific about where the element is
// On your page will cut down on execution/search times
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 to add or remove a class
// From an element depending on the presence of that
// Class. Where some developers wocould use:
A. hasClass ('bluebutton ')? A. removeClass ('bluebutton'): a. addClass ('bluebutton ');
// ToggleClass allows you to easily do this usinga. toggleClass ('bluebutton ');

7. Set the function specified by IE

The Code is as follows:

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

8. Use jQuery to replace an element.

The Code is as follows:

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

9. Verify whether an element is empty

The Code is as follows:

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

10. Search for the index of an element in the unordered set.

The Code is as follows:

$ ("Ul> li"). click (function () {var index = $ (this). prevAll (). length ;});

11. Bind a function to an event

The Code is as follows:

$ ('# Foo'). bind ('click', function () {alert ('user clicked on "foo ."');});

12. Add HTML to an element

The Code is as follows:

$ ('# Lal'). append ('sometext ');

13. Define attributes using objects when creating elements

The Code is as follows:

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

14. filter multiple attributes

The Code is as follows:

// This precision-based approached can be useful when you use
// Lots of similar input elements which have different types
Var elements = $ ('# someid input [type = sometype] [value = somevalue]'). get ();

15. Use jQuery to pre-load images

The Code is as follows:

JQuery. preloadImages = function () {for (var I = 0; I '). attr ('src', arguments [I]) ;};
// Usage mirror.preloadimages('image1.gif ','/path/to/image2.png ', 'some/image3.jpg ');

16. set any event handler that matches a selector
[Code] $ ('button. someClass '). live ('click', someFunction );
// Note that 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 you wocould use ..
//
. Live () $ ("table "). each (function () {$ ("td", this ). live ("hover", function () {$ (this ). toggleClass ("hover ");});});
// Now use ..
$ ("Table"). delegate ("td", "hover", function () {$ (this). toggleClass ("hover ");});

17. Locate the selected option Element

The Code is as follows:

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

18. Hide elements that contain specific values

The Code is as follows:

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

19. Automatically scroll to a specific area of the page

The Code is as follows:

JQuery. fn. autoscroll = function (selector) {$ ('html, body '). animate ({scrollTop: $ (selector ). offset (). top }, 500 );}
// Then to scroll to the class/area you wish to get to like this:
$ ('. Area_name'). autoscroll ();

20. Detect various browsers

The Code is as follows:

Detect Safari (if ($. browser. safari), Detect IE6 and over (if ($. browser. msie & $. browser. version> 6), Detect IE6 and below (if ($. browser. msie & $. browser. version <= 6), Detect FireFox 2 and above (if ($. browser. mozilla & $. browser. version> = '1. 8 '))

21. Replace the word in the string

The Code is as follows:

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

22. Close the right-click menu

The Code is as follows:

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

23. Define a custom Selector

The Code is 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 current element
// Return false to explude current element
};
// Custom Selector usage:
$ ('. SomeClasses: test'). doSomething ();

24. determine whether an element exists

The Code is as follows:

If ($ ('# somediv'). length ){
// Hooray !!! It exists...
}

25. Use jQuery to determine the left and right mouse keys

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

The Code is as follows:

// This snippet will show you 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]) ;}}) ;});

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

The Code is as follows:

// Here's how we used to do it in 1.3.2 using setTimeout
SetTimeout (function () {$ ('. myp'). hide ('blind', {}, 500)}, 5000 );
// And here's how you can do it with 1.4 using the delay () feature (this is a lot like sleep)
$ (". Myp"). delay (5000). hide ('blind', {}, 500 );

28. dynamically create elements to the DOM

The Code is as follows:

Var newgbin1Div = $ ('');
Newgbin1Div. attr ('id', 'gbin1. com '). appendTo ('body ');

29. Limit the number of characters in textarea

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 "){
// 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> 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:
$ ('# Gbin1textarea'). maxLength (500 );

30. Create a basic test case for the function

The Code is as follows:

// Separate tests into modules.
Module ("Module B ");
Test ("some other gbin1.com test", function (){
// Specify how your assertions are expected to run within a test. Exact CT (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 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.