Applying onClick to Element Array in a For Loop

…衆ロ難τιáo~ 提交于 2020-01-14 09:23:07

问题


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)";

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.

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.

What am I doing wrong?


回答1:


The property name is onclick.

onClick even though being valid HTML, does not exist in JS as it is case-sensitive.

Also you have to assign it a function reference or expression as David answered (+1).

Fiddle




回答2:


You need to assign the 'onclick' handler to a function:

for (var i = 0; i < myElems.length; i++)
     myElems[i].onclick = function() { someFunction(this);};

Assigning your 'alert' call directly will fire it (as you're seeing). What you want to do is assign your handler to a function that will be called when the event is fired.



来源:https://stackoverflow.com/questions/12498187/applying-onclick-to-element-array-in-a-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!