表格中偶数/奇数行的jQuery选择器 [英] jQuery selectors for even/odd rows in a table

查看:253
本文介绍了表格中偶数/奇数行的jQuery选择器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

第一个代码块中的代码是源代码.源代码运行后.代码将被更改(请参阅第二个代码块).

The code in the first Code Block is the source code. After the source code is running. The code will be changed (See the 2nd Code Block).

我希望标记的类(即偶数"和奇数")仅显示在"table1"中.但是,目前一个嵌套表(即"table2")还具有每个标记的"even"和"odd"类.

I want the class(i.e. 'even' and 'odd') of tag is only displayed in the 'table1'. However, currently a nest table (i.e. 'table2') also has 'even' and 'odd' class of each tag.

有人可以帮我吗?预先感谢.

Can anyone help me out? Thanks in advance.

-----------第一个代码块--------------

<head>
<script type="text/javascript">
            $(document).ready(function(){
                $("#table1 tr:odd").addClass("odd");
                $("#table1 tr:not(.odd)").addClass("even");  
            });
</script>
</head>

<body>

<table id="table1">
    <tr>
        <td>AAA</td>
        <td>CCC</td>
    </tr>
    <tr>
        <td>BBB</td>
        <td>DDD</td>
    </tr>
    <tr>
        <td>
            <table id="table2">
                   <tr></tr>
                   <tr></tr>
            <table>
        </td>
    </tr>

</table>
</body>

----------第二个代码块---------------

<table id="table1">
    <tr class="even">
        <td>AAA</td>
        <td>CCC</td>
    </tr>
    <tr class="odd">
        <td>BBB</td>
        <td>DDD</td>
    </tr>
    <tr class="even">
        <td>
            <table id="table2">
                   <tr class="even"></tr>
                   <tr class="odd"></tr>
            <table>
        </td>
    </tr>

</table>

推荐答案

所有发布的答案都差不多.

All of the posted answer are almost right..

$(document).ready(function(){
    $("#table1 > tbody > tr:odd").addClass("odd");
    $("#table1 > tbody > tr:not(.odd)").addClass("even");  
});

许多浏览器会自动将tbody添加到表中,即使您自己没有添加.因此#table1 > tr将不匹配,因为tr不是table的直接子代.最好的选择是使用上面的代码,并为那些不适合您的浏览器明确添加tbody.

Many browsers automatically add a tbody to your table even if you don't add one yourself. So #table1 > tr will not match because tr is not a direct child of table. Your best bet is to use the above and explicitly add a tbody for those browsers that don't do it for you.

 <table id="table1">
      <tbody>
        <tr class="even">
            <td>AAA</td>
            <td>CCC</td>
        </tr>
        <tr class="odd">
            <td>BBB</td>
            <td>DDD</td>
        </tr>
        <tr class="even">
            <td>
                <table id="table2">
                   <tbody>
                       <tr class="even"></tr>
                       <tr class="odd"></tr>
                   </tbody>
                <table>
            </td>
        </tr>
      <tbody>

</table>

http://jsfiddle.net/5ETAD/1/

这篇关于表格中偶数/奇数行的jQuery选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆