使用jQuery动态为表中的备选行添加Bgcolor
我创建了一个程序,使用AddRow按钮将行添加到表中。每行作为新行添加到表中。我想为奇数行和偶数行添加不同的背景色。我使用jQuery添加背景,但代码中有一点错误。我的意思是,我可以添加行中的背景色,但它显示不正确 以下是jQuery代码:使用jQuery动态为表中的备选行添加Bgcolor,jquery,html-table,Jquery,Html Table,我创建了一个程序,使用AddRow按钮将行添加到表中。每行作为新行添加到表中。我想为奇数行和偶数行添加不同的背景色。我使用jQuery添加背景,但代码中有一点错误。我的意思是,我可以添加行中的背景色,但它显示不正确 以下是jQuery代码: <script> $(document).ready(function() { var id = 0; // Add button functionality $("#addrow").c
<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>
$(文档).ready(函数(){
var-id=0;
//添加按钮功能
$(“#添加行”)。单击(函数(){
id++;
如果(id%2==0){
$(“.prototype td”).css(“背景色”、“eee”);
}否则{
$(“.prototype td”).css(“背景色”、“ddd”);
}
var master=$(this.parents)(“table.stdform”);
//基于原型行获取新行
var prot=master.find(“.prototype”).clone();
master.find(“.fancyTable tbody”).append(prot);
});
});
以下是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: 从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>
索引为0的行
索引为#1的行
索引为#2的行
索引为#3的行
$(“tr:odd”).css(“背景色”,“#bbff”);
注意html是如何不受任何css样式的影响的,以及jquery是如何在一行中工作的。如果要访问偶数颜色,则始终存在“tr:even”选择器
另一个问题(仅当您不使用回发刷新表并希望实时刷新表时才出现此问题)
添加新行时,可能还会遇到一个问题。您的jquery.ready函数执行一次。。在你的页面准备好之后;因此,由于您通常会在dom上使用jquery代码$(“tr:odd”){…}
来处理您已经拥有的html表元素,因此css样式将只影响这些行,而不会影响之后添加的任何新行
您可以选择捷径,添加与jquery.ready函数相同的代码,并将其应用于您的单击处理程序(如果您的用户有很多要添加的内容,并且您的表很大,则可能会影响性能),或者您可以跟踪表的最后一行,找出其中的奇数或偶数,并在添加新行时以这种方式应用css样式
我会记录下您表中的项目数量,并将该数字用作您要添加的新行的决定因素。您可以使用Jquery和选择器 请尝试以下代码:
$(document).ready(function() {
$("tr:odd").css("background-color","#eee");
$("tr:even").css("background-color","#ddd");
});
这是一个明显的CSS问题-搜索zebra表谢谢@mplungjan,我用
$(“.fancyTable tbody tr:nth child(odd)”)获得它。addClass(“odd”)$(“.fancyTable tbody tr:n个孩子(偶数)”).addClass(“偶数”)代码>