在for循环中将onClick应用于元素数组 [英] Applying onClick to Element Array in a For Loop
问题描述
我正在尝试将onClick事件应用于文档中的元素数组,如下所示:
I am trying to apply an onClick event to an array of elements in a document, like this:
for (var i = 0; i < myElems.length; i++)
myElems[i].onClick = "someFunction(this)";
代码放在body标签的onLoad事件的init()函数内。我注意到当文档加载时,函数不起作用。
The code is placed inside of an init() function for the onLoad event of the body tag. I notice that when the document loads, the functions wont work.
我注意到,如果我添加一个alert()告诉我函数是否是问题:
I've noticed, that if I add an alert() to tell me if the function is the problem:
for (var i = 0; i < myElems.length; i++)
myElems[i].onClick = "alert('It worked!')";
文档将加载并执行所有元素的警报,而不考虑是否或不是我实际点击了元素。
The document will load and perform the alert for all of the elements, without ever taking into consideration whether or not I actually clicked the element.
我做错了什么?
推荐答案
属性名称为 onclick
。
The property name is onclick
.
onClick
即使是有效的HTML,在JS中也不存在它区分大小写。
onClick
even though being valid HTML, does not exist in JS as it is case-sensitive.
此外,您必须为大卫回答(+1)时为其指定函数引用或表达式。
Also you have to assign it a function reference or expression as David answered (+1).
这篇关于在for循环中将onClick应用于元素数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!