0

I am currently working on a basket but cant seem to get the clickHandler function working. When ever I press a button it will always return the "data-id" as 4. Any suggestions? Here is a snippet of code along with a js fiddle.

basket.clickHandler = function(){
    var targets = document.getElementsByClassName("addButton");
    for(var i = 0; i < targets.length; i++) {
        var target = targets[i];
        target.onclick = function() {
            var shopId = target.getAttribute("data-id");
            var item = shop.items[shopId];

            basket.add(item);
        };
    };
};

http://jsfiddle.net/g1L5mwk4/

hudsond7
  • 566
  • 7
  • 21

1 Answers1

0

An explanation of the problem and a general solution can be found here: JavaScript closure inside loops – simple practical example

In your particular example, you should refer to the element itself via this, not the the loop variable:

var shopId = this.getAttribute("data-id");
Community
  • 1
  • 1
Felix Kling
  • 756,363
  • 169
  • 1,062
  • 1,111