首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网络技术 > 网络基础 >

(三)选择元素——(13)链锁作用(Chaining)

2013-09-29 
(3)选择元素——(13)链锁作用(Chaining)The traversal method combinations that we have just explored ill

(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.

链锁如何工作我们将在以后很仔细的讨论一下链锁是如何实现的。现在,只要清楚几乎所有的jquery方法返回一个jquery对象就好了,因此我们可以有更多的jquery方法适用到结果上。It is also possible to break a single line of code into multiple lines for greater readability. For example, a single chained sequence of methods could be written as one line:

$('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" class
Admittedly, 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.
诚然,在这个例子中的DOM遍历的迂回性在一定程度上很荒谬。我们当然不推荐这样使用,因为我们可以使用更加简单的更加直接的方法。这个例子的重点只是展示。
Chaining can be like speaking a whole paragraph's worth of words in a single breath—it gets the job done quickly, but it can be hard for someone else to understand. Breaking it up into multiple lines and adding judicious comments can save more time in the long run.

链锁作用好像就是一口气说了一整段文字——我们很快的完成了这个工作,但是他可能对某些人来说很难理解。把他打断成多行然后添加清晰的注释,从长期来讲将节省更多的时间。

热点排行