我找到了一个脚本来改变每一秒行的颜色,使它看起来不错,但是当我在同一页面上添加另一个表时,它为第一个表着色,但是第二个表没有颜色,为什么这个?
table.js的代码
jQuery(document).ready(function() {
//for tables style
function altRows(id){
if(document.getElementsByTagName){
var table = document.getElementById(id);
var rows = table.getElementsByTagName("tr");
for(i = 0; i < rows.length; i++){
if(i % 2 == 0){
rows[i].className = "evenrowcolor";
}else{
rows[i].className = "oddrowcolor";
}
}
}
}
window.onload=function(){
altRows('alternatecolor');
}
});
php网页代码:
<?php
//first table
echo'
<table class="altrowstable" id="alternatecolor">
<tr>
<th>Seller</th>
<th>price(per 1k doge)</th>
<th>payment allowed</th>
<th>View Trade</th>
</tr>
<td>Example</td>
<td>Example</td>
<td>Example</td>
</tr>';
echo'</table> <br />';
//seccond table
echo '<h3>trades on going </h3>';
echo ' <table class="gridtable">
<table class="altrowstable" id="alternatecolor">
<tr>
<th>Trade User</th>
<th>Cost($)</th>
</tr>
<td>Example</td>
<td>Example</td>
<td>Example</td>
</tr>';
echo'</table> ';
?>
答案 0 :(得分:4)
更好的方法是通过CSS。
tr:nth-child(odd) { background-color: black, color: white }
tr:nth-child(even) { background color: white, color: black }
这将适用于您网页上的所有表格,而不必担心您的PHP或Javascript输出HTML。
答案 1 :(得分:0)
当您致电alternatecolor
时,您正在引用第一个表格,其ID为document.getElementById(id)
。也许在第二个表格中添加一个ID,然后再次为其调用altRows
?
编辑PHP文件中的第二个表:
echo ' <table class="gridtable" id="secondTable">
编辑JavaScript:
window.onload=function(){
altRows('alternatecolor');
altRows('secondTable');
}