访问对象内属性的同级对象,onclick javascript

时间:2018-12-03 22:17:57

标签: javascript object onclick this parent

我正在创建5个objects,每个div属性都附加为sourceonclick应该在iframe中打开相对的html页面。 / p>

需要为i==[i].num上的每个元素访问onclick function的简单值,因此从actor[i].num中选择actor[i].source认为应该很简单。

// html
<div id="op0" class="op"><img src="gfx/0.svg"></div>
<div id="op1" class="op"><img src="gfx/1.svg"></div>
<div id="op2" class="op"><img src="gfx/2.svg"></div>
<div id="op3" class="op"><img src="gfx/3.svg"></div>
<div id="op4" class="op"><img src="gfx/4.svg"></div>

// js
var i=0;
let actor = {};
    for (i = 0; i < 5; i++) { 
        actor[i] = {
            num: i,
            source: document.getElementById('op'+[i]),
            clicked: 0 
        }
        actor[i].source.addEventListener( 'click', function() { 
            console.log(this) // the source attribute <div>
            console.log(this.num) // undefined
            console.log(parent.num) // undefined
            console.log(actor[i].num) // TypeError
            clickActor(i) // returns 5 at the time of click
        });
}

function clickActor(num){
    if (actor[num].open == 0){
        actor[num].source.classList.add("scaleUp");
        document.getElementById("iFrame").src = "op"+num+".html";
        actor[num].open = 1;
        // div to move and scale
    } else {
        actor[num].source.classList.remove("scaleUp");
        document.getElementById("iFrame").src = "";
        document.getElementById("iFrame").style.pointerEvents = "none";
        actor[num].open = 0;
        // div to move and scale back
    }
}

1 个答案:

答案 0 :(得分:1)

var变量是函数作用域,因此您的i变量将在循环中反复使用,因此当您实际单击按钮时,i将是最后一个循环数。您可以通过插入一个自执行函数代替回调函数来简单地创建一个新的函数范围来绕过此操作。

actor[i].source.addEventListener( 'click', (function(i) {
  return (function() { 
    console.log(actor[i].num) // this is should print out the object assign above it
    clickActor(i) // i is now the index of the actor
  });
})(i));