【问题标题】:Possible for jQuery to add a css class to an image if it doesn't have one?如果没有,jQuery 可以向图像添加 css 类吗?
【发布时间】:2012-08-16 20:29:33
【问题描述】:

正如标题所说,我有一个 div。某处(可以嵌入到更多的子 div 中)将是图像。是否可以为该 div 中当前没有样式的所有图像分配样式?

编辑:

<div id="testDiv">
<div>
<img id="testImage1" class="testclass1"/>
<img id="testImage2" />
</div>
<span>
<img id="testImage3"/>
<img id="testImage4" class="testclass2"/>
</span>
</div>

testImage2 和 testImage3(上图)将有一个 testclass3 类分配给它。

【问题讨论】:

  • 您想为没有类别的图像添加不同的类别吗?如果是这样,是否有特定的类将出现在其他图像上?
  • 更具体一些,向我们展示您所要求的一些代码。
  • @Vega - 我不知道我能做到多具体。有一个div。该 div 中的某处(可以嵌套在任意数量的子元素中)将是某处的图像。我想全选。那些没有 css 类的我想分配一个特定的类。
  • @DeeMac 我会发布一些代码或场景示例,以获得更快和最佳的答案。

标签: jquery css image jquery-selectors


【解决方案1】:

使用:not() 选择器查找没有类的元素,然后使用addClass() 添加一个类。

试试这个:

$("img:not([class])").addClass("robasta");

注意:I did a jsFiddle,但要查看结果,您必须通过结果窗格查看 Firebug

【讨论】:

    【解决方案2】:

    试试下面的方法,

    $(function() {
        $('#testDiv').find('img').filter(function (){        
            return this.className == '';  
        }).addClass('yourClass');
    });
    

    演示: http://jsfiddle.net/EXSUN/

    【讨论】:

      【解决方案3】:
      $("#divid").find("img").each(function(index){
       if(undefined==$(this).attr("style")){
        // SET YOU STYLE HERE
       }
      });
      

      【讨论】:

        【解决方案4】:
        $('div').find('img[class=""]').addClass('yourClass');
        

        【讨论】:

        • @Vega - “……目前没有风格”(OP)。非常感谢安德里亚,我想问题解决了,我会试一试。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-10
        • 2016-10-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多