javascript implements the method that table selects a row to highlight with a specified color

  • 2020-06-15 07:35:00
  • OfStack

This article example shows how javascript implements table to highlight selected rows with specified colors. Share to everybody for everybody reference. Specific implementation methods are as follows:


<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>table The selected row is highlighted with the specified color </title>
<script type="text/javascript">
function IniEvent() {
  var tbl = document.getElementById("tblMain");
  var trs = tbl.getElementsByTagName("tr");
  for (var i = 0; i < trs.length; i++) {
 trs[i].onclick = TrOnClick;
  }
}
function TrOnClick() {
  var tbl = document.getElementById("tblMain");
  var trs = tbl.getElementsByTagName("tr");
  for (var i = 0; i < trs.length; i++) {
 if (trs[i] == this) { // Determines whether the row is currently selected 
   trs[i].style.background = "yellow";
 }
 else {
   trs[i].style.background = "white";
 }
  }
}
</script>
</head>
<body onload="IniEvent()">
<table id="tblMain" border="1">
<tr>
  <td>1</td>
  <td>3 star </td>
  <td>AA</td>
</tr>
<tr>
  <td>2</td>
  <td>Norkia</td>
  <td>BB</td>
</tr>
<tr>
  <td>3</td>
  <td> apple </td>
  <td>CC</td>
</tr>
<tr>
  <td>4</td>
  <td> lenovo </td>
  <td>DD</td>
</tr>
</table>
</body>
</html>

Hopefully, this article has been helpful in your javascript programming.


Related articles: