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

Javascript 检查元素是否具有给定数组中的任何属性,javascript,html,attributes,Javascript,Html,Attributes,如果我禁用了属性,,并且我想在运行函数之前检查元素是否具有此属性,那么我可以使用 if element.hasAttribute('disabled') 如果我有几个与同一个函数相关的属性,例如 attributes = [disabled, something, another] 如何使用if element.hasAttribute('attribute')检查数组中的任何属性 更新: 实际上,我的数组中只有两个项目,所以我有 if el.hasAttribute('noink') ||

如果我禁用了属性
,并且我想在运行函数之前检查元素是否具有此属性,那么我可以使用

if element.hasAttribute('disabled')
如果我有几个与同一个函数相关的属性,例如

attributes = [disabled, something, another]
如何使用
if element.hasAttribute('attribute')
检查数组中的任何属性


更新

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

if el.hasAttribute('noink') || el.hasAttribute('disabled')
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);

更紧凑一点

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

或者在全有或全无的情况下为真或假:

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')
if el.hasAttribute('noink') || el.hasAttribute('disabled')

下面的响应也是可行的,如果我有一个更大的数组,我会使用它们。

谢谢,我以后可能会使用类似这样的属性作为属性替代。为什么使用[].slice.call为什么不使用array.slice.call?这两个@adeneoYes之间有什么区别吗?是的,有区别,
[].slice.call
Array.prototype.slice.call的快捷方式。有趣的是,我不会想到这一点。不过,我没有足够的属性来证明这一点。谢谢你的回复。