【问题标题】:What is causing the console error "Cannot read property 'setAttribute' of undefined at HTMLTableRowElement"是什么导致控制台错误“无法读取 HTMLTableRowElement 处未定义的属性‘setAttribute’”
【发布时间】:2020-06-06 20:35:24
【问题描述】:

我目前正在开发 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 行。 是什么导致了这些错误?

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

【问题讨论】:

    标签: javascript google-chrome-extension add-on


    【解决方案1】:

    您已经接近了,只是失去了对所需表格行的引用。一种选择是使用 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>

    【讨论】:

      猜你喜欢
      • 2018-11-10
      • 2018-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-07
      • 1970-01-01
      相关资源
      最近更新 更多