首页 > 解决方案 > 将图标添加到特定的类

问题描述

我是 js 新手,我想学习我所做的,而不是简单地去做。所以这个问题是针对论坛的。我想添加到一个彩色组,一个图标,我有这个代码

<strong>
    <a href="/">
        <span style="color:#B83EE0">
            <strong>USERNAME</strong>
        </span>
    </a>
</strong>

我想给它添加一个图标,我想用js来完成。

我有这段代码,但我现在卡住了,因为我不知道如何按颜色获取元素。

$(function () {
  $('a span[style="color:#6eb1d6;"] strong').each(function () {
    var icon = ' here is the icon';
    $()
  })
});

我想了解我在做什么而不是复制粘贴。谢谢

标签: javascriptjquery

解决方案


试试这个方法。基本上,在 span 的内容前添加一个 img 标签。

$(function() {              

    $('span[style="color:#6eb1d6;"]').each(function() {  
            
        var icon = 'img/icon.jpg';  // your icon image file with right path
        var content = $('span[style="color:#6eb1d6;"]').html();
        $('span[style="color:#6eb1d6;"]').html("<img src='"+icon+"'>"+content);
  
    }); 
}); 

推荐阅读