user1429671
user1429671

Reputation: 69

jQuery .each not returning per-item data as it should

If I output the value of next and prev for each instance of .tile, they appear correctly, however when attempting to use them to select which page to load into their container, it will use the value of next and prev from the last created instances of next and previous, instead of the relevant ones.

What thing did I type wrong?

$(".tile").each(function(){
 var $this = $(this);
     container = $("#container");
     button = $this.find(".button")
     next = button.data("next");
     prev = button.data("prev");
     urls = ["i.html", "b/i.html", "p/i.html"]

 button.on({
  mousedown: function(){
   console.log(urls[next])
    container.empty().load(urls[next])
   }
  })
})

Upvotes: 0

Views: 39

Answers (2)

Roko C. Buljan
Roko C. Buljan

Reputation: 206078

Fixed your code:

// Those two are unnecessary inside the each. Use before the each loop 
var $container = $("#container"),               // use comma while listing variables!
    urls = ["i.html", "b/i.html", "p/i.html"];  // Close listing using ;

$(".tile").each(function(){

  var $this = $(this),                 // use comma while listing variables!
      $button = $this.find(".button"),
      next = $button.data("next"),
      prev = $button.data("prev");     // Close listing using ;

  $button.on({
     mousedown: function(){
       console.log(urls[next]);
       $container.empty().load(urls[next]);
     }
  });

});

Upvotes: 2

Leah Zorychta
Leah Zorychta

Reputation: 13419

That's because you're not instantiating next and prev as new variables for each iteration of the loop. That means in total exactly 1 version of next and prev exist in your entire program and you just keep re-assigning a value to it. Every button listener you make will refer to this same next variable. Use the var keyword inside your loop:

$(".tile").each(function(){
     var $this = $(this);
     var container = $("#container");
     var button = $this.find(".button")
     var next = button.data("next");
     var prev = button.data("prev");
     var urls = ["i.html", "b/i.html", "p/i.html"]

     button.on({
      mousedown: function(){
       console.log(urls[next])
        container.empty().load(urls[next])
      }
     })
})

Upvotes: 2

Related Questions