仅在加载youtube url时修改iframe的src(jQuery或Javascript)



有人可以给我看一个将附加此字符串的javascript吗:

&showinfo=0

到 iframe SRC 属性,但仅当 SRC 包含 youtube.com

因此,此标签:

<iframe width="1280" height="720" src="https://www.youtube.com/embed/Yso_Ez691qw?feature=oembed" frameborder="0" allowfullscreen=""></iframe>

将成为:

<iframe width="1280" height="720" src="https://www.youtube.com/embed/Yso_Ez691qw?feature=oembed&amp;showinfo=0" frameborder="0" allowfullscreen=""></iframe>

但仅在YouTube网址上,而不是其他iframe上。

以下内容将选择在其 src 属性中包含字符串youtube的所有 IFrame,并将字符串&showinfo=0追加到其 src 属性。

$("iframe[src*='youtube']").each(function() {
    var src = $(this).attr('src');
    $(this).attr('src', src + '&showinfo=0');
});

不过,您可能需要根据需要对其进行调整:

  • 例如,您可以检查整个YouTube网址,而不仅仅是"youtube"。

  • 此外,在追加查询字符串之前,您可能需要检查查询字符串是否还不是 URL 的一部分。

好的,

让我们将其分解为步骤:

  1. 循环遍历页面上的每个 iframe
  2. 检查该 iframe 的 src 是否包含"youtube"
  3. 更新 iframe 的 src 属性

这是代码:

$(document).ready(function() {
  // here is the loop
  $('iframe').each(function(i) {
    // here we get the iframe's source
    var src = $(this).attr('src');
    var substring = 'youtube';
    // check if this iframe's source (src) contains 'youtube'
    if(src.indexOf(substring) !== -1) {
      // OK it does - lets update the source (src)
      $(this).attr('src', src + '&showinfo=0');
      console.log($(this).attr('src'));
      // https://www.youtube.com/embed/Yso_Ez691qw?feature=oembed&showinfo=0
    }
  });
});

最新更新