问题
So maybe I'm just not looking in the right places but I can't find a good explanation of how to do the equivalent of jQuery's
$('a').click(function(){
// code here
});
in plain old JavaScript?
Basically I want to run a function every time an a
tag is clicked but I don't have the ability to load jQuery into the page to do it in the way above so I need to know how to do it using plain JavaScript.
回答1:
Working Example: http://jsfiddle.net/6ZNws/
Html
<a href="something">CLick Here</a>
<a href="something">CLick Here</a>
<a href="something">CLick Here</a>
Javascript:
var anchors = document.getElementsByTagName('a');
for(var z = 0; z < anchors.length; z++) {
var elem = anchors[z];
elem.onclick = function() {
alert("hello");
return false;
};
}
回答2:
element.addEventListener('click', function() { ... }, false);
You have to locate the elements and make a loop to hook up each one.
回答3:
Try the following
var clickHandler = function() {
// Your click handler
};
var anchors = document.getElementsByTagName("a");
for (var i = 0; i < anchors.length; i++) {
var current = anchors[i];
current.addEventListener('click', clickHandler, false);
}
Note: As Ӫ_._Ӫ pointed out this will not work on IE8 and lower as it doesn't support addEventListener
.
On IE8 you could use the following to subscribe to onclick
. It's not a perfect substitute as it requires everyone to be cooperative but it may be able to help you out
var subscribeToOnClick = function(element) {
if (element.onclick === undefined) {
element.onclick = clickHandler;
} else {
var saved = element.onclick;
element.onclick = function() {
saved.apply(this, arguments);
clickHandler.apply(this, arguments);
}
}
}
for (var i = 0; i < anchors.length; i++) {
var current = anchors[i];
subscribeToOnClick(current);
}
回答4:
document.getElementById('elementID').onclick = function(){
//click me function!
}
回答5:
Here you go:
[].forEach.call( document.querySelectorAll( 'a' ), function ( a ) {
a.addEventListener( 'click', function () {
// code here
}, false );
});
Live demo: http://jsfiddle.net/8Lvzc/3/
(doesn't work in IE8)
Also, I recommend event delegation...
回答6:
This will assign an onclick
function to every a
element.
var links = document.getElementsByTagName("a");
var linkClick = function() {
//code here
};
for(var i = 0; i < links.length; i++){
links[i].onclick = linkClick;
}
You can see it in action here.
来源:https://stackoverflow.com/questions/7556564/vanilla-javascript-version-of-jquery-click