简体   繁体   English

未捕获的类型错误:c.addEventListener 不是函数……? javascript DOM 事件

[英]Uncaught TypeError: c.addEventListener is not a function…? javascript DOM Event

var c = document.getElementsByClassName("grid-item");
console.log("Connected");
console.log(c);
c.addEventListener("click",function(){
  c.textContent = 'X';
})


c.addEventListener("dblclick",function(){
  c.textContent = 'O';
})

Why my code is not working the addEventListener function show invalid为什么我的代码不起作用 addEventListener function 显示无效

.getElementsByClassName() returns a list of elements.In order to attach an event listener, you need to use a loop or use the index of the element. .getElementsByClassName()返回元素列表。为了附加事件侦听器,您需要使用循环或使用元素的索引。 Please check the below example:请检查以下示例:

 var c = document.getElementsByClassName("grid-item"); console.log("Connected"); console.log(c); c[0].addEventListener("click",function(){ c[0].textContent = 'X'; }) c[0].addEventListener("dblclick",function(){ c[0].textContent = 'O'; })
 <div class="grid-item">Hello</div>

document.getElementsByClassName("grid-item"); will give you an array of elements that have that, even if there's only 1.会给你一个元素数组,即使只有 1 个。

you can use document.getQuerySelector(".grid-item");你可以使用document.getQuerySelector(".grid-item"); instead and that will give you the single element相反,这将为您提供单一元素

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

相关问题 JavaScript 未捕获类型错误:replay.addEventListener 不是 function - JavaScript Uncaught TypeError: replay.addEventListener is not a function addEventListener 事件 Uncaught TypeError: e.stopPropogation is not a function - addEventListener event Uncaught TypeError: e.stopPropogation is not a function 如何在JavaScript中修复“未捕获的TypeError:action.addEventListener不是函数” - How to fix “Uncaught TypeError: action.addEventListener is not a function” in JavaScript 未捕获的TypeError:check.addEventListener不是函数 - Uncaught TypeError: check.addEventListener is not a function 未捕获的类型错误:document.getElementsByClassName(...).addEventListener 不是函数 - Uncaught TypeError: document.getElementsByClassName(...).addEventListener is not a function 未捕获的类型错误:knopkes.addEventListener 不是 function - Uncaught TypeError: knopkes.addEventListener is not a function Javascript-element.addEventListener()返回“未捕获的TypeError” - Javascript - element.addEventListener() returns “Uncaught TypeError” 未捕获到的typeError:input.addEventListener不是函数 - Uncaught typeError : input.addEventListener is not a function 未捕获的类型错误:ele.addEventListener 不是函数 - Uncaught TypeError: ele.addEventListener is not a function 未捕获的TypeError:button.addEventListener不是函数 - Uncaught TypeError: button.addEventListener is not a function
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM