【问题标题】:Add the "class" attribute when checking that the link "img.youtube.com"检查链接“img.youtube.com”时添加“类”属性
【发布时间】:2018-06-13 04:46:27
【问题描述】:

我的例子如下:

<a class="thumb-post" href="#" style="background-image:url(https://img.youtube.com/vi/hKRUPYrAQoE/maxresdefault.jpg)"></a>

检查链接“img.youtube.com”将添加“类”,如下所示:

<a class="thumb-post icon-video" href="#" style="background-image:url(https://img.youtube.com/vi/hKRUPYrAQoE/maxresdefault.jpg)"></a>

【问题讨论】:

  • 您好,欢迎来到 Stack Overflow。你想问如何做到这一点?你真的需要edit你的问题来显示一些你试图这样做的代码,这样我们就可以看到你卡在哪里了。您还应该指出以前的类似问题没有适合您需要的答案。
  • 您是否尝试在单击链接时添加类属性?
  • 此问题无效,很遗憾,我们无法帮助您从头开始编写代码。

标签: javascript


【解决方案1】:

当您在实现算法时遇到问题时,您需要将其拆分为更小的原子任务。在 99.9% 的情况下,互联网包含了这些任务的答案。

要将icon-video 类添加到特定标记的所有元素或\和在其计算的background-image 样式定义中具有“img.youtube.com”的类,您实际上需要执行以下操作:

  1. 首先,您需要找到所有需要处理并且可以包含此链接的候选元素。例如,所有a 标签或所有具有thumb-post 类的元素(您应该自己选择此条件):

  2. 遍历这些元素:

  3. 获取元素的计算背景图像样式值:

  4. 检查此背景图片是否包含“img.youtube.com”字符串:

  5. icon-video 添加到每个匹配的元素:

你的动作!

【讨论】:

    【解决方案2】:

    您无需搜索所有&lt;a&gt; 元素即可添加icon-video 类。您只能使用CSS 来完成此操作,方法是使用 CSS [attribute*=value] 选择器。它选择每个attribute 值包含子字符串"Value" 的元素。所以:

    a[style*="img.youtube.com"] {
        /* This is the same as .icon-video class */
    }
    

    示例:选择每个&lt;a&gt; 元素,其style attribute value 包含子字符串"img.youtube.com"

    .thumb-post {
        display: inline-block;
        width: 50px;
        height: 50px;
        margin: 5px;
        background-size: cover;
        border: 3px solid blue
    }
    
    .thumb-post[style*="img.youtube.com"] {
        border: 3px solid red
    }
    <a class="thumb-post" href="#" style="background-image:url(https://img.youtube.com/vi/hKRUPYrAQoE/maxresdefault.jpg)"></a>
    <a class="thumb-post" href="#" style="background-image:url(https://img.youtube.com/vi/hKRUPYrAQoE/maxresdefault.jpg)"></a>
    <a class="thumb-post" href="#" style="background-image:url(myimage.jpg)"></a>
    <a class="thumb-post" href="#" style="background-image:url(https://img.youtube.com/vi/hKRUPYrAQoE/maxresdefault.jpg)"></a>
    <a class="thumb-post" href="#" style="background-image:url(https://unsplash.it/3000/3000/?random)"></a>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-05
      • 2016-10-17
      • 2011-03-25
      • 2016-01-08
      • 2011-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多