Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
487 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...