简体   繁体   English

无法将事件侦听器添加到HTML元素

[英]Not able to add event listener to HTML element

Not able to add event listener to span element. 无法将事件侦听器添加到span元素。 Please help. 请帮忙。 Please let me know if it is possible to debug this. 请让我知道是否可以调试它。

<html>

<head>
</head>

<body>
    <span id="test">Click me!</span>
    <script>
        var element = document.getElementById('test');
        element.addEventListener('onclick', function ()
        {
            alert('it works!')
        })
    </script>
</body>

</html>

To expand on my comment : 扩展我的评论:

You need to replace "onclick' by "click". 您需要将“ onclick”替换为“ click”。

The "on" prefix is used when you do add the function as the property like domElement.onclick = function () {...} 当您确实将函数添加为domElement.onclick = function () {...}类的属性时,将使用“ on”前缀

 var element = document.getElementById('test'); element.addEventListener('click', function () { alert('it works!') }) 
 <span id="test">Click me!</span> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM