使用jQuery来foreach iframe-src,并通过函数获取ID和操作

Using jQuery to foreach iframe src and get ID and action via functions

本文关键字:函数 获取 ID 操作 jQuery foreach iframe-src 使用      更新时间:2023-09-26

我是jQuery和JS的新手。如何使用jQuery正确重写这些函数?我知道这是标准的JS,它可以很好地处理手动HTML标记,但我现在还需要浏览页面,找到带有YouTube src和ID的iframe,然后用第一个示例标记重新创建它们。

我完全被卡住了。我想我或多或少都有,但现在不确定该去哪里。

Fiddle:https://jsfiddle.net/yurt5bb6/

第一个例子使用我的标记:

<div class="video-container">
   <div class="video-player" data-id="Cv_2mp3X868"></div>
</div>

这是我需要的,但我认为现在我需要在加载时进行foreach,并从iframe嵌入中创建相同的标记——函数应该会更好。

尝试:

function createThumb(id) {
    return '<img class="youtube-thumb" src="//i.ytimg.com/vi/' + id + '/hqdefault.jpg"><div class="play-button"></div>';
}
function createIframe() {
    var iframe = $("iframe");
    iframe.attr("src", "//www.youtube.com/embed/" + this.parentNode.dataset.id + "?autoplay=1&autohide=2&border=0&wmode=opaque&enablejsapi=1&controls=0&showinfo=0");
    iframe.attr("frameborder", "0");
    iframe.attr("id", "youtube-iframe");
    this.parentNode.replaceChild(iframe, this);
}
$(document).ready(function() {
    // build video from default markup
    var defaultVideo = $(".video-player");
    $(defaultVideo).each(function (index, value){
        var p = $('<div></div>');
        p.innerHTML = createThumb(v[n].dataset.id);
        p.onclick = createIframe;
        v[n].appendChild(p);
    });
    // search for social embeds and recreate to our markup
    $('iframe[src*="youtube.com"]').each(function() {
        var loadedVideoURL = $('iframe').attr('src').match(/[^/]*$/)[0];
        console.log(loadedVideoURL);
    }); 
});

我试图清理原生JS和jQuery的混乱混合,并对您的fiddle进行了一些编辑:https://jsfiddle.net/yurt5bb6/2/

默认功能:

(function() {
    $.each($('.video-player'), function() {
        $(this).append(videoThumb($(this).data('id')));
        $(this).on('click', videoIframe);
    });
    $.each($('iframe'), function() {
        // Rebuild the given template
        var player = $('<div class="video-player">');
        // Strip youtube video id for data-id attribute
        var id = $(this).attr('src');
        id = id.substr(id.lastIndexOf("/")+1);
        player.attr('data-id', id);
        player.html(videoThumb(id));
        player.on('click', videoIframe);
        var videoContainer = $('<div class="video-container">');
        videoContainer.append(player);
        $(this).replaceWith(videoContainer);
    });
})();

Iframe渲染功能:

function videoIframe() {
    var iframe = $('<iframe>');
    iframe.attr("src", "//www.youtube.com/embed/" + $(this).attr('data-id') + "?autoplay=1&autohide=2&border=0&wmode=opaque&enablejsapi=1&controls=0&showinfo=0");
    iframe.attr("frameborder", "0");
    iframe.addClass("youtube-iframe");
    $(this).empty();
    $(this).append(iframe);
}

还更改了CSS,为youtube iframe创建了一个类而不是id。