【问题标题】:jQuery .each() Works Only on the Last ElementjQuery .each() 仅适用于最后一个元素
【发布时间】:2012-03-11 14:35:51
【问题描述】:

我正在尝试创建要通过 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>

这是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");
        });
    });
});

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

你可以在这里看到它的实际效果:http://jsfiddle.net/ZJNAa/我错过了什么吗?

【问题讨论】:

  • 我在检查持续时间之后添加了一个警报,看来您的代码也在第二个 div 中填充了第一个持续时间。然后用正确的时间替换它。

标签: javascript jquery iteration


【解决方案1】:

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

如果在声明变量时省略var 关键字,它将被创建为全局变量

您想要的是每个函数的本地变量,因此请确保在它们前面加上 var

请参阅 here 以获取更新且正常工作的 jsFiddle。

【讨论】:

    【解决方案2】:

    您需要在变量前加上var 关键字,否则它们是全局的:

    Modified fiddle

    【讨论】: