javascript - 事件侦听器即使在 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>
解决方案
Document 接口的getElementByClassName方法返回具有所有给定类名的所有子元素的类数组对象。
因此,您可以为其分配一个 ID 并通过 ID 获取它或使用numone[0]
推荐阅读
- java - 带有 RSQL 的 REST 查询语言用于日期字段
- python - 绘制存储为顶点和面的网格
- javascript - React - 安装/卸载的顺序以及如何实现“责任链”
- c++ - 无法区分 JSON 对象/数组/字符串
- jquery - 为文件夹和子文件夹创建 ul 和 li 元素
- php - Python OWASP ZAP API 似乎没有成功验证 http basic
- php - PHP根据给定索引的匹配值合并数组
- ruby-on-rails - 在每个循环中访问belongs_to数据
- azure - 根据结果替换参数
- java - 使用 Apache POI 将工作簿的日期系统设置为 1904