(3)选择元素——(13)链锁作用(Chaining)
The traversal method combinations that we have just explored illustrate jQuery's chainingcapability. With jQuery, it is possible to select multiple sets of elements and do multiple things with them, all within a single line of code. This chaining not only helps keep jQuery code concise, but it also can improve a script's performance when the alternative is to re-specify a selector.
我们探索过的遍历方法范例展示了jquery的链状能力。使用jquery,我们可以选择很多元素组合,然后在他们身上做很多事情,而这只需要一行代码。战中链锁不仅仅让jquery代码变得简洁,而且还能提高在我们重新选择元素时脚本选择元素的性能。
How chaining works
We will explore how chaining is implemented in greater detail later. For now, just realize that almost all jQuery methods return a jQuery object, and so can have more jQuery methods applied to the result.
$('td:contains(Henry)').parent().find('td:eq(1)') .addClass('highlight').end().find('td:eq(2)') .addClass('highlight');也可以被写成多行:
$('td:contains(Henry)') // Find every cell containing "Henry" .parent() // Select its parent .find('td:eq(1)') // Find the 2nd descendant cell .addClass('highlight') // Add the "highlight" class.end() // Return to the parent of the cell containing "Henry" .find('td:eq(2)') // Find the 3rd descendant cell .addClass('highlight'); // Add the "highlight" classAdmittedly, the DOM traversal in this example is circuitous to the point of absurdity. We certainly wouldn't recommend using it, as there are clearly simpler, more direct methods at our disposal. The point of the example is simply to demonstrate the tremendous flexibility that chaining affords us.
链锁作用好像就是一口气说了一整段文字——我们很快的完成了这个工作,但是他可能对某些人来说很难理解。把他打断成多行然后添加清晰的注释,从长期来讲将节省更多的时间。