JavaScript中getAttribute返回undefined问题求助
问题分析与解决方案
我来帮你排查下为啥getAttribute总是返回undefined,主要有这几个问题:
1. getAttribute的参数使用错误
你写的x.getAttribute(className)里,className是未定义的变量!要获取元素的class属性,得把属性名用字符串包裹起来,比如getAttribute('class');其实更简单的方式是直接用DOM元素自带的className属性,不用通过getAttribute也能直接访问。
2. 部分图片的两处错误
- 后面三个
<img>标签的onclick里写的是GoTo(x),这里的x根本没定义,得改成GoTo(this)才能把当前点击的图片元素传递给函数; - 这三个图片还没设置
class属性,就算函数逻辑对了,也拿不到值,得给它们加上对应类名才行。
修正后的完整代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link href="resources/css/Home.css" rel="stylesheet"/> </head> <body> <div id="floatleft"> <img class="ploegen.html" onclick="GoTo(this)" onmouseleave="leave(this)" onmouseover="hover(this)" src="resources/ploegenhome.jpg"> <img class="stadions.html" onclick="GoTo(this)" onmouseleave="leave(this)" onmouseover="hover(this)" src="resources/stadionhome.jpg"> <img class="opstelling.html" onclick="GoTo(this)" onmouseleave="leave(this)" onmouseover="hover(this)" src="resources/opstellinghome.png"> <img class="simulatie.html" onclick="GoTo(this)" onmouseleave="leave(this)" onmouseover="hover(this)" src="resources/simulatiehome.jpg"> </div> <img src="resources/logo_wk_2018.png" id="logowk"> <div id="tekstjes"> <ul> <li><a>Ploegen</a></li> <li><a>Stadions</a></li> <li><a>Opstelling</a></li> <li><a>Simulatie</a></li> </ul> <!-- 这里之前的<ul/>是错误写法,要改成闭合的</ul> --> </div> <p id="lol"></p> <script> function GoTo(x){ // 直接用x.className更简洁,效果和getAttribute('class')一致 var y = x.className; document.getElementById("lol").innerText = y; } function leave(x){ x.style.opacity = 0.5; } function hover(x){ x.style.opacity = 1; var y = x.className; document.getElementById("lol").innerText = y; } </script> </body> </html>
还有个小细节:你代码里的<ul/>是无效的HTML标签写法,已经改成了标准的闭合标签</ul>,避免结构错乱。
现在再运行代码,应该就能正常获取到class属性的值,不会返回undefined啦!
内容的提问来源于stack exchange,提问作者user9710437
相关产品推荐
相关产品推荐

