【问题标题】:Event Listener not working even on chrome?事件监听器即使在 chrome 上也不起作用?
【发布时间】:2019-07-08 17:56:31
【问题描述】:

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

main.js:6 Uncaught TypeError: numone.addEventListener is not a function 在 main.js:6(匿名)@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>

【问题讨论】:

  • 在您的情况下numone 是什么? addEventListerner 应该附加到 DOM 元素
  • 欢迎来到 Stack Overflow!请使用tour(您将获得徽章!),环顾四周,并阅读help center,尤其是How do I ask a good question?,我还推荐Jon Skeet 的Writing the Perfect Question。我们需要更多信息来帮助您,但从根本上说,错误告诉您numone 不是EventTarget(即,不是元素或文档)。
  • 你更新的问题仍然没有提到任何关于numone的内容。

标签: javascript


【解决方案1】:

Document 接口的getElementByClassName 方法返回一个类数组对象,其中包含所有具有给定类名的所有子元素。

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

【讨论】:

    猜你喜欢
    • 2015-06-06
    • 2020-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-24
    • 2013-11-30
    相关资源
    最近更新 更多