我如何为基于 youtube 的 link 添加 class。com/embed URL andress?

How can I add class for the link based on youtube.com/embed URL andress?

我有一个灯箱插件,它使用 lightview class 作为链接。 所以用法看起来像这样:

<a href="https://youtube.com/embed/HPOcZtfjrrU?start=102&autoplay=1" class="lightview">Link for the site</a>

我想为启动此 url 的每个链接添加此 class (lightview):

https://youtube.com/embed/

这是重要的部分:
我不想为这样的链接添加 class:
https://www.youtube.com/watch?v=XtSf8GqrF6Q
因为这个 url 将嵌入我的网站。

使用 jQuery 您可以 select 所有具有以给定值开头的属性的元素,方法是使用 [attribute^=value] select 或。然后你只需要将 lightview class 添加到这些元素。很简单:

$("a[href^='https://youtube.com/embed']").addClass("lightview");

这是一个演示:

$("a[href^='https://youtube.com/embed']").addClass("blue");
a {
    display:block;
    color:red;
}

a.blue {
    color:blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<a href="https://youtube.com/embed/HPOcZtfjrrU?start=102&autoplay=1">Video with right link</a>
<a href="https://www.youtube.com/watch?v=XtSf8GqrF6Q">Video without right link</a>
<a href="http://www.google.com">Link to Google</a>
<a href="https://youtube.com/embed/HPOcZtfjrrU?start=102&autoplay=1">Antoher video with right link</a>
<a href="http://whosebug.com">Another wrong link</a>

您可以使用 Jquery 检索 a 标签,如果 hrefhttps://youtube.com/embed/ 开头,则为每个标签添加 class:

$(function(){
  $("a").each(function(ix, el){
    if(el.href.match("^https://youtube.com/embed/")) {
      $(el).addClass('lightbox');
    }
  })
});

这里是plunk.

jQuery 可用于实现所需的结果,也可在纯 CSS3 中完成,如下所示:

a[href^='https://youtube.com/embed'] {
color:blue;
}

而且因为它不使用任何形式的 JavaScript,所以无论用户是否启用 JavaScript,它都会工作