0

我正在开发一个移动网页,我必须在上面导入两个 youtube 视频。当我单击该视频时,该视频必须展开并开始播放。该视频已使用 javascript 和 html 获得。

我的问题是我已经使用 2 个不同的嵌入式 youtube 代码片段对 javascript 进行了编码,但它采用了 javascript 第二部分的视频代码并将其应用于两个视频。因此,请帮助我让这些视频中的每一个都根据嵌入的代码播放它们各自的视频。

这是jsfiddle: http: //jsfiddle.net/tJpBY/,代码如下:

HTML 代码:

<div class="container">
    <div class="preview">
        <img class="thumb">
        <img class="play" src="https://s-static.ak.fbcdn.net/rsrc.php/v2/yG/r/Gj2ad6O09TZ.png">
    </div>
</div>
<div class="container">
    <div class="preview1">
        <img class="thumb1">
        <img class="play" src="https://s-static.ak.fbcdn.net/rsrc.php/v2/yG/r/Gj2ad6O09TZ.png">
    </div>
</div>

Javascript代码:

var youtube_video_id = "Cgovv8jWETM";
var video_url = "http://youtube.com/watch?v=" + youtube_video_id;
var thumbnail_url = "http://img.youtube.com/vi/" + youtube_video_id + "/1.jpg";
var iframe_url = "http://www.youtube.com/embed/" + youtube_video_id + "?autoplay=1";
var api_url = "https://gdata.youtube.com/feeds/api/videos/" + youtube_video_id + "?  v=2&alt=json-in-script&callback=?";

$(function () {
    // Get video information and set the title.
    $.getJSON(api_url, function (data) {
        $(".info").html("<b><a href='" + video_url + "' target='_blank'>" + data.entry.title.$t + "</a></b>");
    });

    // Set the thumbnail image for the video.
    $(".preview img.thumb").attr("src", thumbnail_url);

    // Switch to the iframe when the image is clicked.
    $(".preview").click(function () {
        $(this).html("<iframe width='400' height='250' src='" + iframe_url + "' frameborder='0' allowfullscreen></iframe>");
        $(this).css("float", "none");
    });
});

var youtube_video_id1 = "rHtVc1asWCc";
var video_url = "http://youtube.com/watch?v=" + youtube_video_id1;
var thumbnail_url = "http://img.youtube.com/vi/" + youtube_video_id1 + "/1.jpg";
var iframe_url = "http://www.youtube.com/embed/" + youtube_video_id1 + "?autoplay=1";
var api_url = "https://gdata.youtube.com/feeds/api/videos/" + youtube_video_id1 + "? v=2&alt=json-in-script&callback=?";

$(function () {
    // Get video information and set the title.
    $.getJSON(api_url, function (data) {
        $(".info").html("<b><a href='" + video_url + "' target='_blank'>" + data.entry.title.$t + "</a></b>");
    });

    // Set the thumbnail image for the video.
    $(".preview img.thumb1").attr("src", thumbnail_url);

    // Switch to the iframe when the image is clicked.
    $(".preview").click(function () {
        $(this).html("<iframe width='400' height='250' src='" + iframe_url + "'  frameborder='0' allowfullscreen></iframe>");
        $(this).css("float", "none");
    });
});

它在 jsfiddle 上运行良好,但是当我在项目中导入相同的代码时,相同的视频会重复两次。所以请帮我解决这个问题。提前致谢。

4

1 回答 1

1

这是修复它的一种方法。

http://jsfiddle.net/tJpBY/2/

您基本上需要重命名.preview.preview1.

$('.preview')将适用于两个视频(以及具有预览类的所有其他内容)。我还编辑了您的一些 css(添加了 preview1)并修复了您的格式错误的 html。

我重命名了比必要更多的东西,因此更容易复制粘贴,这看起来就像你一开始所做的那样。

于 2013-02-18T08:41:10.317 回答