jquery - 使用 jQuery 动态显示表中替代行的 Bgcolor

标签 jquery html-table

我创建了使用“添加行”按钮将行添加到表中的程序。每行都作为新行添加到表中。我想为奇数行和偶数行添加不同的背景颜色。我正在使用 jQuery 添加背景,但我的代码中有一点错误。我的意思是我可以在行中添加背景颜色,但它显示不正确。

这是 jQuery 代码:

<script>
    $(document).ready(function() {
        var id = 0;

        // Add button functionality
        $("#addrow").click(function() {
            id++;

            if(id%2==0){
                $(".prototype td").css("background-color","#eee");
            }else{
                $(".prototype td").css("background-color","#ddd");
            }

            var master = $(this).parents("table.stdform");

            // Get a new row based on the prototype row
            var prot = master.find(".prototype").clone();

            master.find(".fancyTable tbody").append(prot);

        });
    });
</script>

这是html代码:

<html>
<head>
    <title></title>
</head>
<body>
    <table width="100%" cellpadding="0" cellspacing="0" border="0"
    class="stdform">
        ..other codes...
        <tr><td>
        <table class="fancyTable" id="sortable-table"
                cellpadding="0" cellspacing="0" width="100%">
                <thead>
                    <tr>
                        <td>header one</td>
                        <td>header two</td>
                        <td>header three</td>
                    </tr>
                </thead>
                <tbody id="job-tbody">
                    <tr class="prototype">
                        <td>one</td>
                        <td>two</td>
                        <td>three</td>
                    </tr>
                </tody>
        </table>
        </td></tr>
    </table>
</body>
</html>

谢谢,..

最佳答案

您可以使用 css 样式表来完成此操作,也可以使用 jquery 来完成此操作:

http://api.jquery.com/odd-selector/

从 jquery 站点获取代码:

<table border="1">
  <tr><td>Row with Index #0</td></tr>
  <tr><td>Row with Index #1</td></tr>
  <tr><td>Row with Index #2</td></tr>
  <tr><td>Row with Index #3</td></tr>
</table>

<script>
    $( "tr:odd" ).css( "background-color", "#bbbbff" );
</script>

注意 html 是如何不影响任何 css 样式的,以及 jquery 如何在一行中完成工作。如果您想访问偶数颜色,总是有“tr:even”选择器。

http://api.jquery.com/even-selector/

还有一个问题(仅当您不使用回发来刷新表并希望实时刷新时才会出现此问题)

添加新行时您可能还会遇到一个问题。你的 jquery.ready 函数会在你的页面准备好之后执行一次;因此,由于您通常在 dom 上使用 jquery 代码 $( "tr:​​odd"){...} 准备好处理您已有的 html 表元素,因此 css 样式只会影响这些行,而不影响您之后添加的任何新行。

您可以走捷径,添加用于 jquery.ready 函数的相同代码,并将其应用到您的点击处理程序(如果您的用户有很多要添加的内容并且您的表很大,这可能会影响性能) ),或者您可以跟踪表格的最后一行,找出它是奇数还是偶数,并在添加新行时应用 css 样式。

我会持续统计表中的项目数量,并使用该数字作为您要添加的新行的决定因素。

关于jquery - 使用 jQuery 动态显示表中替代行的 Bgcolor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21473861/

相关文章:

函数中的 JQuery 变量有奇怪的行为

javascript - 有没有办法可以淡入 InfoWindow 的自定义内容?

javascript - 使用 Jquery 切换 css 类

csv - 将 d3 生成的 HTML 表导出为 CSV(也必须在 IE 上工作)

html - 使用 ajax 使用 JSON 数据填充现有表

php - 选择两个mysql表中的所有数据

css - 在 td 中对三个表进行居中/样式化(用于响应式电子邮件模板)

Jquery 'Highlight' 具有相同类的元素

HTML 电子邮件 : Images go beyond its limited width in outlook

javascript - 通过 jQuery 重新加载页面