问题
I am trying to addEventListener to all article elements so when they are clicked it turns them into a draggable element.
I'm not using jQuery on this task.
Attempt 1:
document.getElementsByTagName("ARTICLE").addEventListener('click', function(){
document.getElementsByTagName("ARTICLE").setAttribute('draggable', true);});
Attempt 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);
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.
回答1:
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 );
}
回答2:
Well, you have to check for your latters-cases.
But there is another issue, any code related to DOM elements has to be executed when that certain element is load (or is identified by Javascript Engine). The following event (onload) makes sure when the window is load, and then, it executes the closure assigned to. window.onload = function(){}
is what you probably need.
window.onload = function(){
// call your functions or document event listeners here
}
Also TagName, TagNameNS and ClassName all returns a collection which you have iterate through:
var allDivs = document.getElementsByTagName("div");
for(var i = 0; i < allDivs.length; i++)
{
allDivs[i].addEventListener();
}
来源:https://stackoverflow.com/questions/25262824/addeventlistener-to-an-article-element-in-javascript