Html javascript getattribute无法正常工作

时间:2018-05-16 13:25:59

标签: javascript html

我现在已经坚持了一段时间,我不知道什么是错的。 我的getAttribute总是返回undefined .. 我已经尝试了很多,我搞砸了价值和类名,但它总是返回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>

1 个答案:

答案 0 :(得分:4)

错误:

  • 代码的问题在于代码中没有名为ClassName的变量。
  • 另一个错误的是您在onTo函数中使用x代替this
  • 运行代码时发现的另一个小问题是,在<ul>标记的末尾,您使用<ul/>代替</ul>来关闭代码。

修复:

&#13;
&#13;
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;
}
&#13;
<!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>
&#13;
&#13;
&#13;

感谢@RogerC,因为我发现代码中的错误,我认为我修复过了:)