是什么导致控制台错误 "Cannot read property 'setAttribute' of undefined at HTMLTableRowElement"

What is causing the console error "Cannot read property 'setAttribute' of undefined at HTMLTableRowElement"

我目前正在开发 Chrome 扩展。我试图做到这一点,如果你将鼠标悬停在一个元素上,背景会变亮,当你离开它时,它会返回。

if(window.location.pathname == "/page.aspx") {
    tr = document.getElementsByTagName('tr');
    for(i = 0; i < tr.length; i++) {
        tr[i].addEventListener('mouseover', function() {
            tr[i].setAttribute('style', 'background-color: #A9A9A9')
        });
        tr[i].addEventListener('mouseleave', function() {
            tr[i].setAttribute('style', 'background-color: #808080')
        });
    };
};

相反,它什么都不做,当我检查控制台时,我收到十二个错误,说“未捕获的类型错误:无法读取未定义的 属性 'setAttribute' 在 HTMLTableRowElement”,全部用于第 5 行和第 8 行。 是什么导致了这些错误?

EDIT 我必须使用 setAttribute() 来覆盖当前 CSS,这使得无法使用 tr[i].style.backgroundColor

您很接近,只是失去了对所需 table 行的引用。一种选择是使用 this 关键字,因为 TR 可以从其事件侦听器函数中引用自身。

tr = document.getElementsByTagName('tr');
for(i = 0; i < tr.length; i++) {
  tr[i].addEventListener('mouseover', function() {
    this.setAttribute('style', 'background-color: #A9A9A9')
  });
  tr[i].addEventListener('mouseleave', function() {
    this.setAttribute('style', 'background-color: #808080')
  });
};
<table>
  <tr><td>Hi</td></tr>
  <tr><td>There</td></tr>
</table>