14个有用的jQuery技巧,笔记 和最佳实践
来源:广州中睿信息技术有限公司官网
发布时间:2012/10/21 23:25:16 编辑:admin 阅读 318
这篇文章来自http://net.tutsplus.com/tutorials/javascript-ajax/14-helpful-jquery-tricks-notes-and-best-pra

这篇文章来自http://net.tutsplus.com/tutorials/javascript-ajax/14-helpful-jquery-tricks-notes-and-best-practices/,是我在css88网站看到的,贴过来备用。本想翻译的,想想还是看英文比较好,原汁原味。

14 Helpful jQuery Tricks, Notes, and Best Practices

If there is one bad thing about jQuery, it’s that the entry level is so amazingly low, that it tends to attract those who haven’t an ounce of JavaScript knowledge. Now, on one hand, this is fantastic. However, on the flip side, it also results in a smattering of, quite frankly, disgustingly bad code (some of which I wrote myself!).

But that’s okay; frighteningly poor code that would even make your grandmother gasp is a rite of passage. The key is to climb over the hill, and that’s what we’ll discuss in today’s tutorial.


1. Methods Return the jQuery Object

It’s important to remember that most methods will return the jQuery object. This is extremely helpful, and allows for the chaining functionality that we use so often.

view plaincopy to clipboardprint?

  1. $someDiv 
  2.   .attr('class', 'someClass') 
  3.   .hide() 
  4.   .html('new stuff'); 

Knowing that the jQuery object is always returned, we can use this to remove superfluous code at times. For example, consider the following code:

view plaincopy to clipboardprint?

  1. var someDiv = $('#someDiv'); 
  2. someDiv.hide(); 

The reason why we “cache” the location of the someDiv element is to limit the number of times that we have to traverse the DOM for this element to once.

The code above is perfectly fine; however, you could just as easily combine the two lines into one, while achieving the same outcome.

view plaincopy to clipboardprint?

  1. var someDiv = $('#someDiv').hide(); 

This way, we still hide the someDiv element, but the method also, as we learned, returns the jQuery object — which is then referenced via the someDiv variable.


2. The Find Selector

As long as your selectors aren’t ridiculously poor, jQuery does a fantastic job of optimizing them as best as possible, and you generally don’t need to worry too much about them. However, with that said, there are a handful of improvements you can make that will slightly improve your script’s performance.

One such solution is to use the find() method, when possible. The key is stray away from forcing jQuery to use its Sizzle engine, if it’s not necessary. Certainly, there will be times when this isn’t possible — and that’s okay; but, if you don’t require the extra overhead, don’t go looking for it.

view plaincopy to clipboardprint?

  1. // Fine in modern browsers, though Sizzle does begin "running"
  2. $('#someDiv p.someClass').hide(); 
  3. // Better for all browsers, and Sizzle never inits.
  4. $('#someDiv').find('p.someClass').hide(); 

The latest modern browsers have support for QuerySelectorAll, which allows you to pass CSS-like selectors, without the need for jQuery. jQuery itself checks for this function as well.

However, older browsers, namely IE6/IE7, understandably don’t provide support. What this means is that these more complicated selectors trigger jQuery’s full Sizzle engine, which, though brilliant, does come along with a bit more overhead.

Sizzle is a brilliant mass of code that I may never understand. However, in a sentence, it first takes your selector and turns it into an “array” composed of each component of your selector.

view plaincopy to clipboardprint?

  1. // Rough idea of how it works
  2. ['#someDiv, 'p']; 

It then, from right to left, begins deciphering each item with regular expressions. What this also means is that the right-most part of your selector should be as specific as possible — for instance, an id or tag name.

Bottom line, when possible:

  • Keep your selectors simple
  • Utilize the find() method. This way, rather than using Sizzle, we can continue using the browser’s native functions.
  • When using Sizzle, optimize the right-most part of your selector as much as possible.
Context Instead?

It’s also possible to add a context to your selectors, such as:

view plaincopy to clipboardprint?

  1. $('.someElements', '#someContainer').hide(); 

This code directs jQuery to wrap a collection of all the elements with a class of someElements — that are children of someContainer — within jQuery. Using a context is a helpful way to limit DOM traversal, though, behind the scenes, jQuery is using the find method instead.

view plaincopy to clipboardprint?

  1. $('#someContainer') 
  2.   .find('.someElements') 
  3.   .hide(); 
Proof

view plaincopy to clipboardprint?

  1. // HANDLE: $(expr, context)
  2. // (which is just equivalent to: $(context).find(expr)
  3. } else { 
  4. return jQuery( context ).find( selector ); 

3. Don’t Abuse $(this)

Without knowing about the various DOM properties and functions, it can be easy to abuse the jQuery object needlessly. For instance:

view plaincopy to clipboardprint?

  1. $('#someAnchor').click(function() { 
  2. // Bleh
  3.     alert( $(this).attr('id') ); 
  4. }); 

If our only need of the jQuery object is to access the anchor tag’s id attribute, this is wasteful. Better to stick with “raw” JavaScript.

view plaincopy to clipboardprint?

  1. $('#someAnchor').click(function() { 
  2.     alert( this.id ); 
  3. }); 

Please note that there are three attributes that should always be accessed, via jQuery: “src,” “href,” and “style.” These attributes require the use of getAttribute in older versions of IE.

Proof

view plaincopy to clipboardprint?

  1. // jQuery Source
  2. var rspecialurl = /href|src|style/; 
  3. // ...
  4. var special = rspecialurl.test( name ); 
  5. // ...
  6. var attr = !jQuery.support.hrefNormalized && notxml && special ? 
  7. // Some attributes require a special call on IE
  8.     elem.getAttribute( name, 2 ) : 
  9.     elem.getAttribute( name ); 
Multiple jQuery Objects

Even worse is the process of repeatedly querying the DOM and creating multiple jQuery objects.

view plaincopy to clipboardprint?

  1. $('#elem').hide(); 
  2. $('#elem').html('bla'); 
  3. $('#elem').otherStuff(); 

Hopefully, you’re already aware of how inefficient this code is. If not, that’s okay; we’re all learning. The answer is to either implement chaining, or to “cache” the location of #elem.

view plaincopy to clipboardprint?

  1. // This works better
  2. $('#elem') 
  3.   .hide() 
  4.   .html('bla') 
  5.   .otherStuff(); 
  6. // Or this, if you prefer for some reason.
  7. var elem = $('#elem'); 
  8. elem.hide(); 
  9. elem.html('bla'); 
  10. elem.otherStuff(); 

4. jQuery’s Shorthand Ready Method

Listening for when the document is ready to be manipulated is laughably simple with jQuery.

view plaincopy to clipboardprint?

  1. $(document).ready(function() { 
  2. // let's get up in heeya
  3. }); 

Though, it’s very possible that you might have come across a different, more confusing wrapping function.

view plaincopy to clipboardprint?

  1. $(function() { 
  2. // let's get up in heeya
  3. }); 

Though the latter is somewhat less readable, the two snippets above are identical. Don’t believe me? Just check the jQuery source.

view plaincopy to clipboardprint?

  1. // HANDLE: $(function)
  2. // Shortcut for document ready
  3. if ( jQuery.isFunction( selector ) ) { 
  4. return rootjQuery.ready( selector ); 

rootjQuery is simply a reference to the root jQuery(document). When you pass a selector to the jQuery function, it’ll determine what type of selector you passed: string, tag, id, function, etc. If a function was passed, jQuery will then call its ready() method, and pass your anonymous function as the selector.


5. Keep your Code Safe

If developing code for distribution, it’s always important to compensate for any possible name clashing. What would happen if some script, imported after yours, also had a $ function? Bad stuff!

The answer is to either call jQuery’s noConflict(), or to store your code within a self-invoking anonymous function, and then pass jQuery to it.

Method 1: NoConflict

view plaincopy to clipboardprint?

  1. var j = jQuery.noConflict(); 
  2. // Now, instead of $, we use j.
  3. j('#someDiv').hide(); 
  4. // The line below will reference some other library's $ function.
  5. $('someDiv').style.display = 'none'; 

Be careful with this method, and try not to use it when distributing your code. It would really confuse the user of your script! :)

Method 2: Passing jQuery

view plaincopy to clipboardprint?

  1. (function($) { 
  2. // Within this function, $ will always refer to jQuery
  3. })(jQuery); 

The final parens at the bottom call the function automatically – function(){}(). However, when we call the function, we also pass jQuery, which is then represented by $.

Method 3: Passing $ via the Ready Method

view plaincopy to clipboardprint?

  1. jQuery(document).ready(function($) { 
  2. // $ refers to jQuery
  3. }); 
  4. // $ is either undefined, or refers to some other library's function.

6. Be Smart

Remember – jQuery is just JavaScript. Don’t assume that it has the capacity to compensate for your bad coding. :)

This means that, just as we must optimize things such as JavaScript for statements, the same is true for jQuery’s each method. And why wouldn’t we? It’s just a helper method, which then creates a for statement behind the scenes.

view plaincopy to clipboardprint?

  1. // jQuery's each method source
  2.     each: function( object, callback, args ) { 
  3. var name, i = 0, 
  4.             length = object.length, 
  5.             isObj = length === undefined || jQuery.isFunction(object); 
  6. if ( args ) { 
  7. if ( isObj ) { 
  8. for ( name in object ) { 
  9. if ( callback.apply( object[ name ], args ) === false ) { 
  10. break; 
  11.                     } 
  12.                 } 
  13.             } else { 
  14. for ( ; i < length; ) { 
  15. if ( callback.apply( object[ i++ ], args ) === false ) { 
  16. break; 
  17.                     } 
  18.                 } 
  19.             } 
  20. // A special, fast, case for the most common use of each
  21.         } else { 
  22. if ( isObj ) { 
  23. for ( name in object ) { 
  24. if ( callback.call( object[ name ], name, object[ name ] ) === false ) { 
  25. break; 
  26.                     } 
  27.                 } 
  28.             } else { 
  29. for ( var value = object[0]; 
  30.                     i < length && callback.call( value, i, value ) !== false; value = object[++i] ) {} 
  31.             } 
  32.         } 
  33. return object; 
  34.     } 
Awful

view plaincopy to clipboardprint?

  1. someDivs.each(function() { 
  2.     $('#anotherDiv')[0].innerHTML += $(this).text(); 
  3. }); 
  1. Searches for anotherDiv for each iteration
  2. Grabs the innerHTML property twice
  3. Creates a new jQuery object, all to access the text of the element.
Better

view plaincopy to clipboardprint?

  1. var someDivs = $('#container').find('.someDivs'), 
  2.       contents = []; 
  3. someDivs.each(function() { 
  4.     contents.push( this.innerHTML ); 
  5. }); 
  6. $('#anotherDiv').html( contents.join('') ); 

This way, within the each (for) method, the only task we're performing is adding a new key to an array…as opposed to querying the DOM, grabbing the innerHTML property of the element twice, etc.

This tip is more JavaScript-based in general, rather than jQuery specific. The point is to remember that jQuery doesn't compensate for poor coding.

Document Fragments

While we're at it, another option for these sorts of situations is to use document fragments.

view plaincopy to clipboardprint?

  1. var someUls = $('#container').find('.someUls'), 
  2.     frag = document.createDocumentFragment(), 
  3.     li; 
  4. someUls.each(function() { 
  5.     li = document.createElement('li'); 
  6.     li.appendChild( document.createTextNode(this.innerHTML) ); 
  7.     frag.appendChild(li); 
  8. }); 
  9. $('#anotherUl')[0].appendChild( frag ); 

The key here is that there are multiple ways to accomplish simple tasks like this, and each have their own performance benefits from browser to browser. The more you stick with jQuery and learn JavaScript, you also might find that you refer to JavaScript's native properties and methods more often. And, if so, that's fantastic!

jQuery provides an amazing level of abstraction that you should take advantage of, but this doesn't mean that you're forced into using its methods. For example, in the fragment example above, we use jQuery'seach method. If you prefer to use a for or while statement instead, that's okay too!

With all that said, keep in mind that the jQuery team have heavily optimized this library. The debates about jQuery's each() vs. the native for statement are silly and trivial. If you are using jQuery in your project, save time and use their helper methods. That's what they're there for! :)


7. AJAX Methods

If you're just now beginning to dig into jQuery, the various AJAX methods that it makes available to us might come across as a bit daunting; though they needn't. In fact, most of them are simply helper methods, which route directly to $.ajax.

  • get
  • getJSON
  • post
  • ajax

As an example, let's review getJSON, which allows us to fetch JSON.

view plaincopy to clipboardprint?

  1. $.getJSON('path/to/json', function(results) { 
  2. // callback
  3. // results contains the returned data object
  4. }); 

Behind the scenes, this method first calls $.get.

view plaincopy to clipboardprint?

  1. getJSON: function( url, data, callback ) { 
  2. return jQuery.get(url, data, callback, "json"); 

$.get then compiles the passed data, and, again, calls the "master" (of sorts) $.ajax method.

view plaincopy to clipboardprint?

  1. get: function( url, data, callback, type ) { 
  2. // shift arguments if data argument was omited
  3. if ( jQuery.isFunction( data ) ) { 
  4.         type = type || callback; 
  5.         callback = data; 
  6.         data = null; 
  7.     } 
  8. return jQuery.ajax({ 
  9.         type: "GET", 
  10.         url: url, 
  11.         data: data, 
  12.         success: callback, 
  13.         dataType: type 
  14.     }); 

Finally, $.ajax performs a massive amount of work to allow us the ability to successfully make asynchronous requests across all browsers!

What this means is that you can just as well use the $.ajaxmethod directly and exclusively for all your AJAX requests. The other methods are simply helper methods that end up doing this anyway. So, if you want, cut out the middle man. It's not a significant issue either way.

Just Dandy

view plaincopy to clipboardprint

联系我们CONTACT 扫一扫
愿景:成为最专业的软件研发服务领航者
中睿信息技术有限公司 广州•深圳 Tel:020-38931912 务实 Pragmatic
广州:广州市天河区翰景路1号金星大厦18层中睿信息 Fax:020-38931912 专业 Professional
深圳:深圳市福田区车公庙有色金属大厦509~510 Tel:0755-25855012 诚信 Integrity
所有权声明:PMI, PMP, Project Management Professional, PMI-ACP, PMI-PBA和PMBOK是项目管理协会(Project Management Institute, Inc.)的注册标志。
版权所有:广州中睿信息技术有限公司 粤ICP备13082838号-2