jQuery .each()仅适用于最后一个元素

abh*_*sek 5 javascript iteration jquery

我正在尝试创建一个通过YouTube获取的视频列表.这是我的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>
Run Code Online (Sandbox Code Playgroud)

这是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");
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

该脚本应该适用于类名为"vid_thumb"的所有锚点.但它只适用于最后一个元素.

你可以在这里看到它:http://jsfiddle.net/ZJNAa/我错过了什么?

Gre*_*egL 12

是的,这是一个经典的Javascript错误.

如果var在声明变量时省略关键字,则会将其创建为全局变量.

你想要的是每个函数的局部变量,所以一定要用它们作为前缀var.

请参阅此处了解更新且有效的jsFiddle.