Two very useful custom selectors in the jQuery library are :oddand :even. Let's take a look at how we can use one of them for basic table striping, given the following tables:
<h2>Shakespeare's Plays</h2><table><tr><td>As You Like It</td><td>Comedy</td><td></td></tr><tr><td>All's Well that Ends Well</td><td>Comedy</td><td>1601</td></tr><tr><td>Hamlet</td><td>Tragedy</td><td>1604</td></tr><tr><td>Macbeth</td><td>Tragedy</td><td>1606</td></tr><tr><td>Romeo and Juliet</td><td>Tragedy</td><td>1595</td></tr><tr><td>Henry IV, Part I</td><td>History</td><td>1596</td></tr><tr><td>Henry V</td><td>History</td><td>1599</td></tr></table><h2>Shakespeare's Sonnets</h2><table><tr><td>The Fair Youth</td><td>1–126</td></tr><tr><td>The Dark Lady</td><td>127–152</td></tr><tr><td>The Rival Poet</td><td>78–86</td></tr></table>
tr {background-color: #fff;}.alt {background-color: #ccc; }
Finally, we write our jQuery code, attaching the class to the odd-numbered table rows (<tr>tags):
$(document).ready(function() {$('tr:even').addClass('alt');});
現在我們在樣式表中添加一個影響所有表的行的樣式,然後使用alt類影響所有的偶數行:
最後,我們寫下一個jquery代碼,綁定這個類到表的所有的偶數行(<tr>標籤)But wait! Why use the :evenselector for odd-numbered rows? Well, just as with the :eq()selector, the :evenand :oddselectors use JavaScript's native zero-based numbering. Therefore, the first row counts as 0 (even) and the second row counts as 1 (odd), and so on. With this in mind, we can expect our simple bit of code to produce tables that look similar to the following screenshot:
$(document).ready(function() {$('tr:nth-child(odd)').addClass('alt');});
As before, note that :nth-child()is the only jQuery selector that is one-based. To achieve the same row striping as we did above—except with consistent behavior for the second table—we need to use oddrather than evenas the argument. With this selector in place, both tables are now striped nicely, as shown in the following screenshot:
$(document).ready(function() {$('tr:nth-child(odd)').addClass('alt');$('td:contains(Henry)').addClass('highlight');});
So, now we can see our lovely striped table with the Henryplays prominently featured:
Admittedly, there are ways to achieve the row striping and text highlighting without jQuery—or any client-side programming, for that matter. Nevertheless, jQuery, along with CSS, is a great alternative for this type of styling in cases where the content is generated dynamically and we don't have access to either the HTML or server-side code.
有一點特別需要說明的是:contains()選取器是大小寫敏感的,使用$("td:contains(henry)"),而不是使用大寫的H,將不會選擇任何元素。誠然,我們有很多方法在不使用jquery可以實現給表加上條紋和文字高亮的目的——或者是任何瀏覽器端的編程。但是,使用jquery和css,是實現這種類型的修飾的特別好的選擇,尤其是在內容是動態添加的而且我們不能接觸到html或者伺服器端代碼的情況下。