I'm a bit confused by why this function always sets the h1#attack
to the first element of the hero.attacks
-array, when any li.attack
is clicked? I'm trying to make set it to the corresponding hero.atatcks
-element's name. I've tried with both a for-loop and a foreach and an index set outside of the loop which 'm increasing for every iteration, but nothing seems to work?
http://jsfiddle.net/47r768p8/2/
Javascript:
var hero = {
attacks: [{
name: "atck1"
}, {
name: "atck2"
}, {
name: "atck3"
}, {
name: "atck4"
}]
};
var attacks = document.getElementsByClassName("attack");
for (var i = 0; i < attacks.length; i++) {
var atck = hero.attacks[i];
attacks[i].addEventListener("click", function (event) {
document.getElementById("attack").innerText = atck.name;
})
}
HTML:
<ul>
<li class="attack">Atck1</li>
<li class="attack">Atck2</li>
<li class="attack">Atck3</li>
<li class="attack">Atck4</li>
</ul>
<h1 id="attack"></h1>