You're setting the onclick
attribute to the array of elements, not to each element individually like you need. Also, you're defining show
after you've used it.
var elts = document.getElementsByTagName('a');
var show = function() { alert('hahahha'); }
for (var i = elts.length - 1; i >= 0; --i) {
elts[i].onclick = show;
}
It's more efficient to iterate backwards through the array than to test elts.length
each time through. If you need to iterate forward, store the array length in a variable for better efficiency.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…