$(document).ready(function() {$('td:contains(Henry)').next().addClass('highlight');});
The tables should now look similar to the following screenshot:
$(document).ready(function() { $('td:contains(Henry)').next().addClass('highlight');});
The .next()method selects only the very next sibling element. To highlight all of the cells following the one containing Henry, we could use the .nextAll()method instead:
$(document).ready(function() {$('td:contains(Henry)').nextAll().addClass('highlight');});
As the cells containing Henryare in the first column of the table, this code causes the rest of the cells in these rows to be highlighted, as shown in the following screenshot:$(document).ready(function() { $('td:contains(Henry)').nextAll().addClass('highlight');});
$(document).ready(function() {$('td:contains(Henry)').nextAll().andSelf() .addClass('highlight');});
为了包含最开始的方块(包含Henry文字的那一个)和后面的方块一起,我们添加l.andSelf()方法,如下:$(document).ready(function() {$('td:contains(Henry)').nextAll().andSelf() .addClass('highlight');});
With this modification in place, all of the cells in the row get the styling offered by the highlightclass, as follows:
To be sure, there are a multitude of selector and traversal-method combinations by which we can select the same set of elements. Here, for example, is another way to select every cell in
each row where at least one of the cells contains Henry:
$(document).ready(function() {
$('td:contains(Henry)').parent().children().addClass('highlight');
});
Here, rather than traversing across to sibling elements, we travel up one level in the DOM to the <tr>with .parent()and then select all of the row's cells with .children().
为了确定,有很多选择器和遍历的方法的范例,通过他们我们可以选择相同的元素集合。比如,在这里有另外一个选择至少有一个方格含有Henry的一行每一个元素的方法:
$(document).ready(function() {
$('td:contains(Henry)').parent().children().addClass('highlight');
});
在这里,我们没有遍历兄弟节点,我们向上走了一层,通过.parent()找到了tr元素,然后通过.children()找到了这一行的所有元素。