The jQuery selectors that we have explored so far allow us to select a set of elements as we navigate across and down the DOM tree and filter the results. If this were the only way to select elements, then our options would be quite limited (although, frankly, the selector expressions are robust in their own right, especially when compared to the regular DOM scripting options). There are many occasions when selecting a parent or ancestor element is essential; that is where jQuery's DOM traversal methods come into play. With these methods at our disposal, we can go up, down, and all around the DOM tree with ease.
到目前为止我们探索过的jquery选择器允许我们在操纵DOM树的时候选择一串元素,然后过滤结果。如果只有一种方法选择元素,我们的选择将会受到限制(尽管,坦白说,和原生的DOM选择器比起来,这些选择器表达式凭他们本身已经非常健壮了)有很多情况下选择一个父元素或者祖先元素是必须的,这就是jQuery的DOM遍历方法出现的原因。通过这些方法,我们可以很容易的遍历整个DOM树。
Some of the methods have a nearly identical counterpart among the selector expressions. For example, the line we first used to add the altclass, $('tr:even').addClass('alt'), could be rewritten with the .filter()method as follows:
$('tr').filter(':even').addClass('alt');
For the most part, however, the two ways of selecting elements complement each other. Furthermore, the .filter()method
in particular has enormous power because it can take a function as its argument. The function allows us to create complex tests for whether elements should be kept in the matched set. Let's suppose, for example, we want to add a class to all external links.
jQuery has no selector for this sort of case. Without a filter function, we'd be forced to explicitly loop through each element, testing each one separately. With the following filter function, however, we can still rely on jQuery's implicit iteration and
keep our code compact:
$('a').filter(function() {return this.hostname && this.hostname != location.hostname;}).addClass('external');
1. They must have a hrefattribute with a domain name (this.hostname). We use this test to exclude mailtolinks, for instance.
2. The domain name that they link to (again, this.hostname) must not match (!=) the domain name of the current page (location.hostname).
更精确的说,.filter()方法迭代调用匹配的元素集合,为每一个元素调用函数,然后检查返回值。如果返回false,这个元素将被从匹配的元素集合中移除。如果返回值是true,这个元素将会被保留,,如下:
In the next section, we'll take another look at our
striped tables to see what else is possible with traversal methods.
在下面的小节,我们将再看一下我们加了条纹的列表去查看一下通过遍历方法,我们还能做到哪些事情。