未捕获类型错误:对象#&LT;&的NodeList GT;没有法“的addEventListener” [英] Uncaught TypeError: Object #<NodeList> has no method 'addEventListener'
问题描述
我在一个相对简单的HTML文件的一个按钮元件。我想添加事件侦听器,但我不断收到错误,我不知道为什么:未捕获类型错误:对象#&LT;&的NodeList GT;没有法的addEventListener
我想学习的addEventListener方法,但我不明白这有什么错我在做什么:
HTML
&LT;按钮和GT;猜&LT; /按钮&GT;
JS:
VAR则myButton = document.getElementsByTagName('按钮');myButton.addEventListener(点击,DoSomething的,虚假的);VAR的doSomething =功能(E){
的console.log(我被点击了!'); 亦即preventDefault();
返回false;
};
感谢您对那些谁帮助。
总之对可能遇到此问题的任何其他新手:
- 当您使用
document.getElementsByTagName()
或返回的NodeList任何其他方法,你必须指定要处理的节点。 - 确保您添加事件侦听器的 的功能已经被宣布之后。
的getElementsByTagName('按钮')
返回一个列表,而不是元素。您需要将您的EventListener添加到该列表中的第一个元素。
尝试:
VAR则myButton = document.getElementsByTagName('按钮')[0];
I have one button element in a relatively simple HTML file. I'm trying to add an event listener, but I keep getting errors, and I'm not sure why: Uncaught TypeError: Object #<NodeList> has no method 'addEventListener'
I am trying to learn the 'addEventListener' method, but I'm not understanding what's wrong with what I'm doing:
HTML:
<button>guess</button>
JS:
var myButton = document.getElementsByTagName('button');
myButton.addEventListener('click', doSomething, false);
var doSomething = function(e){
console.log('I was clicked!');
e.preventDefault();
return false;
};
Thank you to those who helped.
In conclusion for any other newbies that might be having this problem:
- When you use
document.getElementsByTagName()
or any other method that returns a NodeList, you have to specify which node you want to manipulate. - Make sure you add the event listener after the function has been declared.
getElementsByTagName('button')
returns a list, not an element. You need to add your EventListener to the first element in that list.
Try:
var myButton = document.getElementsByTagName('button')[0];
这篇关于未捕获类型错误:对象#&LT;&的NodeList GT;没有法“的addEventListener”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!