addEventListener到Javascript中的article元素 [英] addEventListener to an article element in Javascript
问题描述
我正在尝试将AddEistener添加到所有文章元素中,因此当它们被单击时会将它们变成一个可拖动的元素。
I am trying to addEventListener to all article elements so when they are clicked it turns them into a draggable element.
我没有在此任务上使用jQuery。
I'm not using jQuery on this task.
尝试1:
document.getElementsByTagName("ARTICLE").addEventListener('click', function(){
document.getElementsByTagName("ARTICLE").setAttribute('draggable', true);});
尝试2:
function draggableTrue() {
var addDrag = document.getElementsByTagName("article");
addDrag.setAttribute('draggable', true);
}
//add event listener to articles
var draggableArticles = document.getElementsByTagName("article");
draggableArticles.addEventListener('onclick', draggableTrue);
两者都得到未捕获的TypeError:undefined不是函数,这通常指出我我错过了什么,但在读完之后我无法弄清楚是什么。
In both I am getting a "Uncaught TypeError: undefined is not a function" which usually points out I am missing something, but after reading up I can't figure out what.
推荐答案
document.getElementsByTagName返回一个集合。因此,您需要迭代它以添加事件侦听器。此集合是本机DOM节点集合而不是jquery集合,因此您无法在集合上使用addEventListener。
document.getElementsByTagName returns a collection. So you need to iterate over it to add the event listeners. This collection is native DOM nodes collections and not a jquery collection hence you cannot use the addEventListener on the collection.
var articles = document.getElementsByTagName("ARTICLE");
var eventListener = function(){console.log('clicked an articles')}
for(var i=0; i<articles.length; i++){
articles[i].addEventListener('click', eventListener );
}
这篇关于addEventListener到Javascript中的article元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!