如何调整此代码以重置过去选定行的颜色

时间:2018-03-11 21:41:20

标签: javascript

如何调整此代码,以便在选择行时颜色会发生变化,但也会重置其他任何已单击回原始颜色的内容。显然,现在它会改变每次点击的行颜色,并且所有过去选定的行颜色保持不变。

var tr = document.getElementById("r_row" + r);
for (var c = 0; c < columns; c++) {
    var td = document.createElement("td");
    td.innerText = cellText[c];
    tr.appendChild(td);

    //Makes the rows selectable

    tr.onclick = function(event) {
        selectedItem = this;
        selectedItem.style.background = "#828891";

    }
}

1 个答案:

答案 0 :(得分:2)

另一种方法是添加一个类,即selected,并使用可选TR的集合检查选定的TR

&#13;
&#13;
var trs = Array.from(document.querySelectorAll('[id^="r_row"]'));
trs.forEach(function(elem) { 
  elem.addEventListener('click', function() {
    trs.forEach(function(tr) {
      if (tr !== elem) tr.classList.remove('selected');
    });
    
    this.classList.add('selected');
  });
});

function addTRs(ids) {
  var columns = 3;
  ids.forEach(function(r) {
    var tr = document.getElementById("r_row" + r);
    for (var c = 0; c < columns; c++) {
      var td = document.createElement("td");
      td.innerText = `This is a test - ${r}`;
      tr.appendChild(td);
    }
  });
}

addTRs([1, 2]);
&#13;
.selected {
  background-color: #828891;
}

tr {
  cursor: pointer
}
&#13;
<table>
  <tbody>
    <tr id='r_row1'></tr>
    <tr id='r_row2'></tr>
    <tr>
      <td colSpan='3'>Not selectable!</td>
    </tr>
  </tbody>
</table>
&#13;
&#13;
&#13;