0

I am trying to

  • Retrieve 2 columns from MySQL and display them in HTML table
  • When clicked on Name which is in the table header i want to change the color of all the contacts.

what I hv done- callin a javascript on tableRows id to change color,but it only changes the the color of 1st row.

<?php
  while($row_color_test = mysql_fetch_assoc($result_color_test))
  {
    ?>
      <tr id="tableRows">
        <td><?php echo $row_color_test['name'] ; ?></td>
        <td><?php echo $row_color_test['phone']; ?></td>
      </tr>
    <?php 
  }
    ?>

Javascript Function

function changecolor()
    {
     document.getElementById("tableRows").style.color="red";
    }

any idea why it happening although all the rows are dynamically created by while loop so all hv the same id and therefore,CSS rule sud apply on them.

Or is there a better way to do it??I hv to use Javascript only

4

1 回答 1

5

但它只会改变第一行的颜色。

正确的。是在行tableRows id上,并且值在页面上必须是唯一的。您不能有多个元素(在本例中为行)具有相同的. 如果你这样做了,大多数浏览器只会忽略页面上的后续元素——所以你只会看到一个元素被更新。ididid

可以使用 aclass代替:

<tr class="tableRows" ...

...并在大多数浏览器上执行此操作:

var list = document.querySelectorAll(".tableRows");
var index;
for (index = 0; index < list.length; ++index) {
    ilst[index].style.color = "red";
}

但最好还是在表格上设置一个类并使用 CSS 规则将行变为红色。

document.getElementById("id_of_the_table").className += " foo";

...使用这个 CSS:

.foo tr {
    color: "red"
}
于 2013-07-05T11:14:18.100 回答