addEventListener(单击)在页面加载时触发

时间:2012-11-27 16:11:29

标签: javascript html javascript-events

我可能......现在,但为什么这个代码在我的页面加载时记录hello x2,而在点击LI-element时没有任何内容?它应该记录单击的元素名称。如果我将“hello”更改为e.target,它会记录HTMLDocument吗?!

谢谢。

<!DOCTYPE html>
<html>
    <head>

        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

        <script type="text/javascript">

            window.onload = function(){
                var list = document.getElementById("listan");

                list.addEventListener("touchstart", elementClicked(event), false);
                list.addEventListener("click", elementClicked(event), false);
            }

            function elementClicked(e) {

                console.log("hello");

                if(e.target && e.target.nodeName == "LI") {

                    console.log(e.target.nodeName);
                }

            }

        </script>


        <style>

            * {
                list-style: none;
                margin: 0;
                padding: 0;
                box-sizing: border-box;
            }

            li {
                width: 90%;
                background: darkblue;
                color: #eee;
                margin: 10px auto;
                padding: 15px;
                border: 1px solid black;
                text-align: center;
                font-family: calibri;
                cursor: pointer;
            }
            ul {
                background: green;
                padding: 10% 0;
            }

        </style>

    </head>
    <body>
        <ul id="listan">
            <li>apa</li>
            <li>häst</li>
            <li>ko</li>
            <li>elefant</li>
            <li>lejon</li>
            <li>zebra</li>
            <li>myrslok</li>
            <li>grävling</li>
        </ul>
    </body>
</html>

1 个答案:

答案 0 :(得分:4)

对于这些:

list.addEventListener("touchstart", elementClicked(event), false);
list.addEventListener("click", elementClicked(event), false);

你希望传递实际的函数elementClicked,所以只需使用:

list.addEventListener("touchstart", elementClicked, false);
list.addEventListener("click", elementClicked, false);