作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我目前正在开发 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'” at HTMLTableRowElement”,全部针对第 5 行和第 8 行。是什么导致了这些错误?
编辑我必须使用 setAttribute() 来覆盖当前的 CSS,这使得无法使用 tr[i].style.backgroundColor
最佳答案
您已经很接近了,只是失去了对所需表格行的引用。一种选择是使用 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>
关于javascript - 是什么导致控制台错误 "Cannot read property ' setAttribute' of undefined at HTMLTableRowElement”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60355160/
我是一名优秀的程序员,十分优秀!