Earlier we added a highlightclass to all cells containing the text Henry. To style the cell next to each cell containing Henry, we can begin with the selector that we have already written, and simply call the .next()method on the result, as follows:
$(document).ready(function() {$('td:contains(Henry)').next().addClass('highlight');});
The tables should now look similar to the following screenshot:
之前,我們為所有包含文本Henry的方格添加了一個highlight類。為了給每一個包含Henry下一個方格加樣式,我們可以以我們已經寫下的選取器開始,然後僅僅在結果中調用一下.next()方法,如下:
$(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:
.next()方法僅僅選擇了恰好挨著的兄弟節點。為了讓包含Henry元素後面的所有的方塊高亮,我們應該使用.nextAll()方法:
$(document).ready(function() { $('td:contains(Henry)').nextAll().addClass('highlight');});
$(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:
$(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().