所以我试图设置.onclick函数,它们会改变我点击的任何对象的颜色到大量的对象,让我们说它们是<div>
个对象。
var myArrayOfObjects = [...]; //get desired <div>s here
for(var i = 0; i < myArrayOfObjects.length; i++){
myArrayOfOjects[i].onclick = myFunction(i);
}
function myFunction(index){
//Make some edit to the <div> myArrayOfObjects[i] here
}
但是设置object.onclick
等于任何带任何参数的函数会使函数自动运行,而不是在单击特定对象时运行。如果我尝试以任何方式访问我而不是传递它,它将始终导致myArrayOfObjects.length
。有没有办法让点击的<div>
确切地识别出哪个对象被点击了,这样就知道要改变哪一个?
答案 0 :(得分:-1)
DO THIS
var myArrayOfObjects = [...]; //get desired <div>s here
for(var i = 0; i < myArrayOfObjects.length; i++){
myArrayOfOjects[i].onclick = function () {
//Make some edit to the <div> myArrayOfObjects[i] here
// here "this" will reder to "myArrayOfObjects[i]" So, you can do something to that div like this
// this.doSomething()
};
}