2017-01-31 43 views
0

我想檢查iframe url中是否存在'autoplay'屬性。如果該屬性不存在,我想添加'自動播放'。如果存在,我想將'autoplay = 1'的值更改爲'autoplay = 0',反之亦然。檢查iframe中是否存在自動播放屬性src

我有動態src的iframe。現在,每當我點擊播放圖標自動播放屬性附加爲https://www.youtube.com/embed/fffjZpMIHk?autoplay=1?autoplay=1。所以我想檢查屬性是否存在,然後需要追加。

<div class="video-container" id="video-container"> 
    <iframe src="https://www.youtube.com/embed/fffjZpMIHk" frameborder="0" allowfullscreen=""></iframe> 

現在我使用的腳本:

$(".playButton").on('click',function() { 
    $(".flex-active-slide iframe")[0].src += "?autoplay=1"; 
    $('.flex-active-slide').contents().find("iframe").attr('src', function(i, oldSrc) { 
    return oldSrc.replace('autoplay=0', 'autoplay=1'); 
    }); 
}); 

樣品小提琴:Demo

+0

分享在問題編輯此的jsfiddle您的代碼示例 - http://jsfiddle.net/ifinto/o2gxgz9r/ –

+0

請檢查我的更新後 – user3386779

回答

2

請您嘗試使用下面的代碼:

$(function() { 
    $(".playButton").on('click',function() { 
     var iframeObj = $(".flex-active-slide iframe")[0]; 
     var currentURL = iframeObj.src; 

     if(currentURL.indexOf("autoplay=") == -1) 
     { 
      //autoplay not present in src; so lets add it 
      currentURL = currentURL + '?autoplay=1' 
     } 
     else{ 
      if(currentURL.indexOf("autoplay=1")>-1){ 
       //replace autoplay=1 with autoplay=0 
       currentURL = currentURL.replace('autoplay=1', 'autoplay=0'); 
      } 
      else 
      { 
       //replace autoplay=0 with autoplay=1 
       currentURL = currentURL.replace('autoplay=0', 'autoplay=1'); 
      } 
     } 

     iframeObj.src = currentURL; //set the newer src to iframe 

    }); 
}); 
0

您可以使用match字符串方法。在下面檢查。

var isAutoPlay = "https://www.youtube.com/embed/jebJ9itYTJE?autoplay=0".match(/autoplay=([^&]*)/); 
if (isAutoPlay && isAutoPlay[1] == 1) { 
    return oldSrc.replace('autoplay=0', 'autoplay=1'); 
} 

工作示例:https://jsfiddle.net/ramsunvtech/dyutu19f/3/