Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .each() Works Only on the Last Element

I am trying to create a list of videos to be fetched via YouTube. Here is my HTML:

  <ul class="videos-list">
<li>
  <a href="#" class="vid_thumb">
      <img src="http://placehold.it/120x90&amp;text=Loading+.+.+." class="yt_thumb" data-url="http://gdata.youtube.com/feeds/api/videos/f_JRZI9o49w?v=2&amp;alt=jsonc" alt="" />
  <span class="duration">Loading...</span></a>
  <h5><a href="#"></a></h5>
</li>

<li>
  <a href="#" class="vid_thumb">
      <img src="http://placehold.it/120x90&amp;text=Loading+.+.+." class="yt_thumb" data-url=
  "http://gdata.youtube.com/feeds/api/videos/uHUHFthr2QA?v=2&amp;alt=jsonc" alt="" />
  <span class="duration">Loading...</span></a>
  <h5><a href="#"></a></h5>
</li>

And here is the javascript:

$(function() {
    /**
     * Set up JSON parsing for video pages
     */
    $("a.vid_thumb").each(function(i) {
        $this = $(this);
        feed_url = $this.children(".yt_thumb").attr("data-url");
        $.getJSON(feed_url, function(json) {
            $title = json.data.title;
            $url = json.data.player.
        default;
            $thumb = json.data.thumbnail.sqDefault;
            $duration = json.data.duration;
            $likes = json.data.likeCount;
            $views = json.data.viewCount;
            $this.next("h5").html("<a href=" + $url + ">" + $title + "</a>");
            $this.children(".duration").html($duration);
            $this.children(".yt_thumb").attr("src", $thumb);
            $this.next("span.view_count").html($views + " Views");
            $this.next("span.upload_date").html($likes + " Likes");
        });
    });
});

The script is supposed to work on all anchors with class name "vid_thumb". But it works only on the last element.

You can see it in action here: http://jsfiddle.net/ZJNAa/ Am I missing something?

like image 681
abhisek Avatar asked Feb 21 '12 09:02

abhisek


1 Answers

Yes, this is a classic Javascript mistake.

If you omit the var keyword when declaring a variable, it will be created as a global variable.

What you want are variables local to each function, so make sure to prefix them all with var.

See here for an updated and working jsFiddle.

like image 59
GregL Avatar answered Sep 28 '22 00:09

GregL