如何选择所有< a>标记和注册onclick事件? [英] How to select all <a> tag and register onclick event?
问题描述
我正在尝试在页面中选择所有< a>
标记,并注册 onclick
甚至给他们。
I am trying to select all the <a>
tags in the page and register onclick
even to them.
我的代码:
document.getElementsByTagName('a').onclick = show;
var show = function(){
alert('hahahha');
}
它不起作用,我的大脑现在油炸了。有任何想法吗?非常感谢。
It doesn't work and my brain is fry now. Any ideas? Thanks a lot.
推荐答案
您正在设置 onclick
属性元素数组,而不是像你需要的那样单独的每个元素。此外,您在使用它之后定义 show
。
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;
}
通过数组向后迭代比测试<$ c $更有效率c> elts.length 每次都通过。如果需要向前迭代,请将数组长度存储在变量中以提高效率。
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.
这篇关于如何选择所有< a>标记和注册onclick事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!