检查元素是否具有给定数组中的任何属性

check if an element has any attribute from a given array

如果我有一个属性disabled,我想在运行一个函数之前检查一个元素是否有这个属性,我可以使用

if element.hasAttribute('disabled')

如果我有多个属性与同一个功能相关,例如

attributes = [disabled, something, another]

如何使用 if element.hasAttribute('attribute') 检查数组中的任何属性?

更新:

实际上我的数组中只有两个项目,所以我做了

if el.hasAttribute('noink') || el.hasAttribute('disabled')

下面的回复也是可行的,如果我有更大的数组,我会使用它们。

申请循环:

  var isAttr=false;
    for(key in attributes){
        if(element.hasAttribute('attribute')){
        console.log('the attribute'+attributes[key]+ 'is attach to element');
        isAttr=true;
       }
    }
 console.log('element has any of array element as attribute:'+isAttr)

一个函数怎么样

function hasAttributes(element, arr) {
    return [].slice.call(element.attributes).some(function(attr) {
        return arr.indexOf(attr.name) !== -1;
    });
}

用作

var attributes = ['disabled', 'something', 'another'];
var element    = document.getElementById('some_id');

var has_attr   = hasAttributes(element, attributes);

FIDDLE

更紧凑一点...

function hasAttributes(e, l){
    var t = [];
    for(var i in l){
        t.push(e.attributes[l[i]] !== undefined);
    }
    return t;
}

使用:

var myList = ["disabled", "something", "another"];
var myElement = document.getElementById("test");
console.log(hasAttributes(myElement, myList));

或者对于全有或全无的情况只是真假:

function getAttributes(e, l){
    var t = [];
    for(var i in l){
        if(e.attributes[l[i]] === undefined){
            return false;
        }
    }
    return true;
}

更新:

实际上我的数组中只有两个项目,所以我做了

if el.hasAttribute('noink') || el.hasAttribute('disabled')

下面的回复也是可行的,如果我有更大的数组,我会使用它们。