我被困在这个问题上有一段时间了,我不知道出了什么问题。 我的 getAttribute 总是返回 undefined.. 我已经尝试了很多,我弄乱了值和类名,但它总是返回未定义的。 请帮助某人
<!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 onclick="GoTo(x)" onmouseleave="leave(this)" onmouseover="hover(this)" src="resources/stadionhome.jpg">
<img onclick="GoTo(x)" onmouseleave="leave(this)" onmouseover="hover(this)" src="resources/opstellinghome.png">
<img onclick="GoTo(x)" 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/>
</div>
<p id="lol"></p>
<script>
function GoTo(x){
var y = x.getAttribute(className);
document.getElementById("lol").innerText = y;
}
function leave(x){
x.style.opacity = 0.5;
}
function hover(x){
x.style.opacity = 1;
var y = x.getAttribute(className);
document.getElementById("lol").innerText = y;
}
</script>
</body>
</html>
最佳答案
错误:
- 您的代码的问题在于没有名为
ClassName
的变量在你的代码中。 - 另一件错误的事是你使用了
x
在 goTo 的 onClick 函数中而不是this
- 我在运行代码时发现的另一个小问题是在你的
<ul>
末尾您使用的标签<ul/>
而不是</ul>
关闭标签。
修复:
function GoTo(x){
var y = x.getAttribute("class");
document.getElementById("lol").innerText = y;
}
function leave(x){
x.style.opacity = 0.5;
}
function hover(x){
x.style.opacity = 1;
var y = x.getAttribute('class');
document.getElementById("lol").innerText = y;
}
<!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 onclick="GoTo(this)" onmouseleave="leave(this)" onmouseover="hover(this)" src="resources/stadionhome.jpg">
<img onclick="GoTo(this)" onmouseleave="leave(this)" onmouseover="hover(this)" src="resources/opstellinghome.png">
<img 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>
</div>
<p id="lol"></p>
</body>
</html>
感谢@RogerC,他发现了我认为我已经修复的代码中的错误 :)
关于javascript - HTML javascript getattribute 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50372205/