首页 文章

按属性选择元素

提问于
浏览
246

我有一组带有生成ID的复选框,其中一些有额外的属性 . 是否可以使用JQuery来检查元素是否具有特定属性?例如,我可以验证以下元素是否具有属性“myattr”?属性的值可以变化 .

<input type="checkbox" id="A" myattr="val_attr">A</input>

例如,如何逐个检查具有此属性的所有复选框的集合?这可能吗?

13 回答

  • 362

    你的意思是你可以选择它们吗?如果是,那么是:

    $(":checkbox[myattr]")
    
  • 1
    if ($('#A').attr('myattr')) {
        // attribute exists
    } else {
        // attribute does not exist
    }
    

    EDIT:

    myattr 存在但是为空字符串或"0"时,上述内容将落入 else -branch . 如果这是一个问题,你应该在 undefined 上明确测试:

    if ($('#A').attr('myattr') !== undefined) {
        // attribute exists
    } else {
        // attribute does not exist
    }
    
  • 8

    我知道问题问题已经很长时间了,但我发现支票更加清晰:

    if ($("#A").is('[myattr]')) {
        // attribute exists
    } else {
        // attribute does not exist
    }
    

    (在本网站上找到here

    有关 is 的文档可以在here找到

  • 1

    在JavaScript中,......

    null == undefined
    

    ...返回 true * . 这是 ===== 之间的区别 . 此外,可以定义名称 undefined (它不是像 null 这样的关键字),所以你最好还是检查其他方式 . 最可靠的方法可能是比较 typeof 运算符的返回值 .

    typeof o == "undefined"
    

    然而,在这种情况下,与null相比应该起作用 .

    *假设 undefined 实际上是未定义的 .

  • 188

    这将有效:

    $('#A')[0].hasAttribute('myattr');
    
  • 0

    $("input[attr]").length 可能是更好的选择 .

  • 166

    使用“typeof”,jQuery“.is”和“.filter”时,有几个想法被抛出,所以我想我会发布一个快速的比较它们 . typeof似乎是最好的选择 . 虽然其他工作正常,但在为此工作调用jq库时似乎存在明显的性能差异 .

  • 4
    $("input#A").attr("myattr") == null
    
  • 8

    只是:

    $('input[name*="value"]')
    

    更多信息:official docs

  • -5
    if (!$("#element").attr('my_attr')){
      //return false
      //attribute doesn't exists
    }
    
  • 5

    除了选择具有属性 $('[someAttribute]')$('input[someAttribute]') 的所有元素之外,您还可以使用函数对对象执行布尔检查,例如在单击处理程序中:

    if(! this.hasAttribute('myattr') ) { ...

  • 1

    我已经创建了具有预期行为的npm包,如上所述 .

    链接到[npm][github]

    用法很简单 . 例如:

    <p id="test" class="test">something</p>
    $("#test").hasAttr("class")
    

    返回true .

    也适用于camelcase .

  • 0

    JQuery将该属性作为字符串返回 . 因此,您可以检查该字符串的长度以确定是否已设置:

    if ($("input#A").attr("myattr").length == 0)
     return null;
    else
     return $("input#A").attr("myattr");
    

相关问题