Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
223 views
in Technique[技术] by (71.8m points)

draggable - addEventListener to an article element in Javascript

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 );
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...