Best Practices and Commonly Made Mistakes
Related Question: jQuery pitfalls to avoid
Remember to use $(document).ready
1.记得用 $(document).ready
If your code is somehow manipulating the DOM, then you need to either wrap it in a$(document).ready(function() {...});
block or move it to the end of your HTML.
Cache your jQuery Objects and Chain Whenever Possible
2.如果可能的话,缓存你的 jQuery 对象,并且链式使用
The jQuery function $()
is expensive. Calling it repeatedly is extremely inefficient. Avoid doing this:
$('.test').addClass('hello');
$('.test').css('color','orange');
$('.test').prop('title','Hello world');
Better, cache your jQuery object in a variable:
var $test = $('.test');
$test.addClass('hello');
$test.css('color','orange');
$test.prop('title','Hello world');
Best, chaining used to reduce repetition:
$('.test').addClass('hello').css('color','orange').prop('title','Hello world');
Variable Naming Conventions
3.变量命名约定
jQuery wrapped variables are usually named starting with $
to distinguish them from standard JavaScript objects.
var $this = $(this);
Know Your DOM Properties and Functions
4.知道你的DOM的属性和方法
While one of the goals of jQuery is to abstract away the DOM, knowing DOM properties can be extremely useful. One of the most commonly made mistakes by those who learn jQuery without learning about the DOM is to Utilize the awesome power of jQuery to access properties of an element:
$('img').click(function(){
$(this).attr('src');// Bad!});
In the above code, this
refers to the element from which the click event handler was fired. The code above is both slow and verbose; the code below functions identically and is much shorter, faster and readable.
$('img').click(function(){this.src;// Much, much better});
Idiomatic Syntax for Creating Elements
5.用易读懂的方式创建元素
Although the following two examples seem to be functionally equivalent and syntactically correct, the first example is preferred:
$('<p>',{
text:'This is a '+ variable,"class":'blue slider',
title: variable,
id: variable + i
}).appendTo(obj);
By comparison, a string concatenation approach is much less readable and far more brittle:
$('<p class="blue slider" id="'+ variable + i +'" title="'+ variable +'">This is a '+ variable +'</p>').appendTo(obj);
While the first example will be slower than the second, the benefits of greater clarity will likely outweigh the nominal speed differences in all but the most performance-sensitive applications.
Moreover, the idiomatic syntax is robust against the injection of special characters. For instance, in the 2nd example, a quote character in variable
would prematurely close the attributes. Doing the proper encoding by yourself remains possible even if not recommended because error prone
摘自