添加YouTube嵌入式视频标题 [英] Append YouTube embedded video title

查看:169
本文介绍了添加YouTube嵌入式视频标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to loop over every YouTube video in a page (using the iframe embed method) and append to each the title of the video, using jQuery. My HTML looks something like this:

<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看起来像这样:

And the jQuery looks like this:

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。然后我使用视频源检索标题,并将其附加到视频容器

So, I am (trying to) take each video and use a regex to extract the ID. I then use the video feed to retrieve the title, and append it to the video-container.

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

This is in a jsFiddle. As you can see, the problem is that the title of each video is appended every time. Where am I going wrong, and is this an efficient way to achieve what I am after?

推荐答案

video variable指的是与选择器.video-container匹配的整个对象集,因此当您执行时

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>');

每个人都这样做。

你需要做的是:

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>');
  });         
});

videoBox变量指向该视频的特定div。

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

这篇关于添加YouTube嵌入式视频标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆