0

我正在尝试遍历页面中的每个 YouTube 视频(使用iframeembed 方法)并使用 jQuery 附加到每个视频的标题。我的 HTML 看起来像这样:

<div class="video-wrapper">
  <div class="video-container">
    <iframe src="http://www.youtube.com/embed/qzNSsDD_LzE" frameborder="0" allowfullscreen></iframe>
  </div>
</div>
<div class="video-wrapper">
  <div class="video-container">
    <iframe src="http://www.youtube.com/embed/9bZkp7q19f0" frameborder="0" allowfullscreen></iframe>
  </div>
</div>

jQuery 看起来像这样:

var video = $('.video-container');
video.each(function() {
  var youTuberegex = /(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com(?:\/embed\/|\/v\/|\/watch\?v=))([\w-]{10,12})/g,
      videoID = youTuberegex.exec($(this).find('iframe').attr('src'))[1];

  $.getJSON('http://gdata.youtube.com/feeds/api/videos/'+videoID+'?v=2&alt=jsonc', function(data){
    var videoTitle = data.data.title;
    video.after('<figcaption>'+videoTitle+'</figcaption>');
  });         
});

所以,我(试图)拍摄每个视频并使用正则表达式来提取 ID。然后我使用视频提要检索标题,并将其附加到video-container.

这是在jsFiddle中。如您所见,问题在于每次都附加每个视频的标题。我哪里出错了,这是实现我所追求的有效方法吗?

4

1 回答 1

1

The video variable refers to the entire set of objects that match the selector ".video-container" so when you are doing

video.after('<figcaption>'+videoTitle+'</figcaption>');

It is doing that on each one.

What you need to do is something like:

video.each(function() {
  var videoBox = $(this)
  var youTuberegex = /(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com(?:\/embed\/|\/v\/|\/watch\?v=))([\w-]{10,12})/g,
      videoID = youTuberegex.exec($(this).find('iframe').attr('src'))[1];

  $.getJSON('http://gdata.youtube.com/feeds/api/videos/'+videoID+'?v=2&alt=jsonc', function(data){
    var videoTitle = data.data.title;
    videoBox.after('<figcaption>'+videoTitle+'</figcaption>');
  });         
});

The videoBox variable points to the specifc div for that video.

于 2013-01-15T16:59:52.713 回答