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
509 views
in Technique[技术] by (71.8m points)

jquery - How to add a onclick event to an element using javascript

I have created an element using document.getElementsByClassname, and would like to add a onclick event to this element, so that when someone clicks on this element onclick function should be called.

I tried with event listener, but this will execute even when I don't click on any function. Using jQuery we can do that by binding a click event, but I my requirement is in javascript/

Thanks!

element.addEventListener("click", alert('clicked'), false);// Add onclick eventListener 

var element= document.getElementsByClassName('classname');
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

getElementsByClassName returns an HTMLCollection, so even though you have only one element with that classname in DOM, you have to retrieve it with index 0:

var element = document.getElementsByClassName('classname')[0];
element.addEventListener("click", function(e) {
    alert('something');
}, false);

Alternatively, since you only have one element with the classname, you can safely use querySelector, which will return the first match element.

var element = document.querySelector('.classname');
                                      ^

element.addEventListener("click", function(e) {
    alert('something');
}, false);

Please note the dot in above code. querySelector accepts a CSS selector string as a parameter.


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

1.4m articles

1.4m replys

5 comments

57.0k users

...