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

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

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


当前回答

我已经创建了npm包与预期的行为如上所述。

链接到[npm]和[github]

用法非常简单。例如:

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

返回true。

骆驼皮也适用。

其他回答

$("输入(attr]”)。长度可能是更好的选择。

这是可行的:

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

要选择具有特定属性的元素,请参阅上面的答案。

为了确定给定的jQuery元素是否具有特定的属性,我使用了一个小插件,如果ajQuery集合中的第一个元素具有此属性,则返回true:

/** hasAttr
 ** helper plugin returning boolean if the first element of the collection has a certain attribute
 **/
$.fn.hasAttr = function(attr) {
   return 0 < this.length
       && 'undefined' !== typeof attr
       && undefined !== attr
       && this[0].hasAttribute(attr)
}

要获得基于多个属性的所有复选框元素的集合,例如在本例中是id和myattr:

var checkboxCollection = $(":checkbox[id][myattr]");

如果你需要为集合中的每个复选框分配事件处理程序:

$(":checkbox[id][myattr]").change(function() {
    if(this.checked) {
        var valueOfAttribute = $(this).attr('myattr');
        // code here
    }
    else{
        // code here
    }
});

如果属性出现在给定的HTML元素中,我们可以很容易地访问value属性。

var offORonlinePath="../img/";   //We can easy to change the path anytime
var extension=".webp"; //we can later change any value like png,jpg,...

$("img[data-src]").each(function(){
  var imgName=$(this).data("src");

  $(this).attr("src",offORonlinePath+imgName+extension);

})