【问题标题】:how to check whether an image have alt attribute or not in jqueryjquery如何判断图片是否有alt属性
【发布时间】:2015-06-01 16:23:33
【问题描述】:

如果图像具有 alt 属性,我想将一个类添加到图像,将一个类添加到没有 alt 属性的图像。

我试过了,但它不起作用

if ($(img).hasAttr('alt'))
{
    this.addClass("haveAlt");   
}

【问题讨论】:

    标签: javascript jquery addclass hasattr


    【解决方案1】:

    你可以使用属性选择器:

    $('img[alt]').addClass('haveAlt');
    

    对于没有alt 属性的,使用:not 选择器:

    $('img:not([alt])').addClass('noAlt');
    

    作为在一个函数调用中处理这两种情况的旁注,您可以使用:

    $('img').addClass(function(){
        return this.alt ? "haveAlt": "noAlt";
    });
    

    【讨论】:

    • 谢谢你..它的工作,但我也想为没有 alt 属性的图像添加类
    • @simr 更新答案,使用 :not() 选择器
    • 非常感谢... (y) 现在一切正常 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-15
    • 2010-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多