10 09/2014

jquery best practices 2

最后更新: Wed Sep 10 2014 12:37:50 GMT+0800

Methods Return the jQuery Object

少 遍历DOM(traverse the DOM) 。赋值、操作一行

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

The Find Selector

jquery 的 Sizzle 引擎尽量会用浏览器内置的 QuerySelectorAll。所以下面代码 后者效率高

// Fine in modern browsers, though Sizzle does begin "running"  
$('#someDiv p.someClass').hide();  

// Better for all browsers, and Sizzle never inits.  
$('#someDiv').find('p.someClass').hide(); 

另外,即便使用 Sizzle,选择器 右边 尽量优化!

Context Instead?

原因同上(后者效率高)

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

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

其实,第二句等于

$('#someContainer')  
  .find('.someElements')  
  .hide(); 

Don’t Abuse $(this)

不要滥用 $(this),能 this 就不需要 jquery 包装。

Accessing Native Properties and Methods

// OPTION 1 - Use jQuery  
var id = $('#someAnchor').attr('id');  

// OPTION 2 - Access the DOM element  
var id = $('#someAnchor')[0].id;  

// OPTION 3 - Use jQuery's get method  
var id = $('#someAnchor').get(0).id; 

// OPTION 3b - Don't pass an index to get  
anchorsArray = $('.someAnchors').get();  
var thirdId = anchorsArray[2].id; 

Conditionally Loading jQuery

本机调试时,不用老等

  
  
  

A Single Hover Function

原来是

$('#someElement').hover(function() {  
  // mouseover  
}, function() {  
 // mouseout  
}); 

现在可简化为(如何只是 toggle 的话)

$('#someElement').hover(function() {  
  // the toggle() method can be used here, if applicable  
}); 

Note that this isn’t an old vs. new deal. Many times, you’ll still need to pass two functions to hover, and that’s perfectly acceptable. However, if you only need to toggle some element (or something like that), passing a single anonymous function will save a handful of characters or so!

Passing an Attribute Object

原来

$('<a />')  
  .attr({  
    id : 'someId',  
    className : 'someClass',  
    href : 'somePath.html'  
  }); 

简写为

$('</a>', {  
    id : 'someId',  
    className : 'someClass',  
    href : 'somePath.html'  
}); 

via 14 Helpful jQuery Tricks, Notes, and Best Practices