首页 > 解决方案 > 事件侦听器即使在 chrome 上也不起作用?

问题描述

我正在尝试向我的 js 添加事件侦听器,但它不适用于 chrome。chrome的错误消息是-

main.js:6 Uncaught TypeError: numone.addEventListener is not a function at main.js:6 (anonymous) @ main.js:6

var numone = document.getElementsByClassName("feature-box");
var numtwo = document.getElementsByClassName("feature-box2");
var addsum = document.getElementsByClassName("add-sum");

numone.addEventListener('click', function()
{
    alert("hii yash!");
}
, false);

//here's the HTML code(only the body tag)-

<body>
        <header>
            <nav>
        <ul>
            <li><a href="index.html">home</a></li>
            <li><a href="menu.html">Menu</a></li>
            <li><a href="location.html">location</a></li>
            <li><a href="contacts.html">contact</a></li>
        </ul>
        <h1>Home</h1>
        </nav>
        </header>
        <section>
            <div><input class = "feature-box"></input></div>
            <div><input class = "feature-box2" /></div>
            <div><p class = "add-sum" ></p></div>
            </section>
            <footer>footer</footer>
            <script src="main.js"></script>
    </body>

标签: javascript

解决方案


Document 接口的getElementByClassName方法返回具有所有给定类名的所有子元素的类数组对象。

因此,您可以为其分配一个 ID 并通过 ID 获取它或使用numone[0]


推荐阅读