30 jquery Code Development tips you should know

Source: Internet
Author: User

1. Create a nested filter

. Filter (": Not (: Have (. selected))")//Remove all elements that do not contain a class of. Selected

2. Reusing your element query

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

JQuery 1.4.* includes support for the Have method. This method would find//if a element contains a certain other element class or whatever it is//you be looking for and Do anything your want to them. $ ("input"). has (". Email"). AddClass ("Email_icon");

4. Use jquery to toggle Styles

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

5. Limit the selected area

Where possible, pre-fix your class names with a tag name//so that jQuery doesn ' t has to spend more time searching//fo R the element you ' re after. Also Remember that anything//you can does to being more specific about where the element is//on your page would cut down on ex Ecution/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

Toggle class allows you to add or remove a class//from an element depending on the presence of that//class. Where some developers would use:a.hasclass (' BlueButton ')? A.removeclass (' BlueButton '): A.addclass (' BlueButton '); Toggleclass allows you to easily does this using A.toggleclass (' BlueButton ');

7. Set the functions specified by IE

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

8. Use jquery to replace an element

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

9. Verify that an element is empty

if ($ (' #keks '). HTML ()) {//nothing found;}

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

$ ("ul > Li"). Click (function () {var index = $ (this). Prevall (). length;});

11. Bind a function to an event

$ (' #foo '). Bind (' click ', function () {alert (' User clicked on ' foo. ');});

12. Add HTML to an element

$ (' #lal '). Append (' Sometext ');

13. Use objects to define attributes when creating elements

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

14. Filter multiple properties using filters

This precision-based approached can is useful when your use//lots of similar input elements which has different types V AR elements = $ (' #someid Input[type=sometype][value=somevalue] '). get ();

15. Pre-load pictures with jquery

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

$ (' Button.someclass '). Live (' click ', someFunction); Note that in JQuery 1.4.2, the delegate and Undelegate options has been//introduced to replace live as they offer Bett ER support for the 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 option element that is selected

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

18. Hide elements that contain specific values

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

19. Automatically scroll to specific areas of the page

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

Detect Safari (if ($.browser.safari)), Detect IE6 and Over (if ($.browser.msie &amp;&amp; $.browser.version &g T 6)), Detect IE6 and below (if ($.browser.msie &amp;&amp; $.browser.version &lt;= 6)), Detect FireFox 2 and a Bove (if ($.browser.mozilla &amp;&amp; $.browser.version &gt;= ' 1.8 ')) 21. Replace a word in a string

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

22. Close the right-click menu

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

23. Define a custom Selector

$.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 Inc Lude current element//Return false to explude current element}; Custom Selector Usage: $ ('. Someclasses:test '). dosomething ();

24. Determine if an element exists

if ($ (' #someDiv '). length) {//hooray!!! it exists ...}

25. Use jquery to determine the left and right mouse clicks

$ ("#someelement"). Live (' click ', Function (e) {if (!$.browser.msie &amp;&amp; E.button = = 0) | | ($.browser.msie &amp;&amp; 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

This snippet would show you what to keep a default value//in a text input field for when a user hasn ' t entered in//a Val UE to replace it swap_val = []; $ (". Swap"). each (function (i) {swap_val[i] = $ (this). Val (); $ (this). Focusin (The 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)

Here's how we used to do it in 1.3.2 using SetTimeout setTimeout (function () {$ ('. Mydiv '). Hide (' blind ', {}, 500)}, 5000 ); And here's how are you can does it with 1.4 using the delay () feature (this is a IoT like sleep) $ (". Mydiv"). ' Blind ', {}, 500);

28. Dynamically creating elements to the DOM

var newgbin1div = $ ('); NEWGBIN1DIV.ATTR (' id ', ' gbin1.com '). AppendTo (' body ');

29. Limit the number of characters in textarea

JQuery.fn.maxLength = function (max) {This.each (function () {var type = This.tagName.toLowerCase (); var inputtype = This.ty Pe? This.type.toLowerCase (): null; if (type = = "Input" &amp;&amp; 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 hasselect Ion = Document.selection? Document.selection.createRange (). Text.length &gt; 0:this.selectionstart! = this.selectionend; Return! (This.value.length &gt;= Max &amp;&amp; (KeyCode &gt; | | keycode = = + | | keycode = 0 | | keycode = =) &amp;&amp;!ob.ctrlkey &amp;&amp; !ob.altkey &amp;&amp;!hasselection); }; This.onkeyup = function () {if (this.value.length &gt; max) {this.value = this.value.substring (0,max);}}; } }); }; Usage: $ (' #gbin1textarea '). MaxLength (500);

30. Create a basic test case for a function

Separate tests into modules. Module ("Module B"); Test ("Some other gbin1.com test", function () {//specify How many assertions is 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"); });

30 jquery Code Development tips you should know

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.