0

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>
Mobilpadde
  • 1,871
  • 3
  • 22
  • 29
  • Actually it always returns the last one because your objects are of reference type, but because your array has same items you think it's the first one :) – Yauheni Leichanok Apr 26 '15 at 19:30
  • 1
    I think this may be a classic case of using the same variable in a loop. See http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – jwatts1980 Apr 26 '15 at 19:31
  • @YauheniLeichanok Made a typo copy/pasting it from my code, anywho, it's only using the last one for some reason? – Mobilpadde Apr 26 '15 at 19:33
  • Check the link that @jwatts1980 posted - it has a great explanation. – Yauheni Leichanok Apr 26 '15 at 19:35
  • @jwatts1980 If you post it as an answer, I'll accept it...that or should I just delete my question? – Mobilpadde Apr 26 '15 at 19:41
  • @Mobilpadde The question has been closed because it was marked as a duplicate. I was creating an answer but was not able to post it before the question was closed. – jwatts1980 Apr 26 '15 at 19:42
  • @jwatts1980 Oh, well... I wish I'd give you some points for helping me out, but if you're not able to post an answer, it's gonna be tough. (Already upvoted your comment) – Mobilpadde Apr 26 '15 at 19:47
  • Not a problem. Happy to help :) – jwatts1980 Apr 26 '15 at 19:53

1 Answers1

0

Your array hero.attacks consists of the same item, iterated several times, which is why it appears that it is setting the same item every time. Try the following:

var hero = {
    attacks: [{
        name: "atck1"
    }, {
        name: "atck2"
    }, {
        name: "atck3"
    }, {
        name: "atck4"
    }]
};
A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76