2015-04-23 49 views
0

如果我有一個屬性disabled,我想檢查元素是否具有運行函數之前這個屬性,我可以使用檢查元素是否具有從給定陣列的任何屬性

if element.hasAttribute('disabled') 

如果我有幾個屬性,涉及到相同的功能,如

attributes = [disabled, something, another] 

如何使用if element.hasAttribute('attribute')檢查陣列中任何的屬性?

更新

我其實只是在我的陣列中的兩個項目,所以我也

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

下的反應也是可行的,如果我有一個較大的陣列我會使用它們。

回答

2

怎麼樣功能

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

+0

謝謝,我將來可能會使用類似於[classie](https://github.com/desandro/classie)的屬性。 – offthegrass

+0

爲什麼你使用[] .slice.call爲什麼不是Array.slice.call?這兩個是否有區別@adeneo –

+0

是的,有一個區別,'[] .slice.call'是'Array.prototype.slice.call'的快捷方式# – adeneo

0

申請循環:

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) 
+0

有趣,我不會有這個。不過,我沒有足夠的屬性來保證它。感謝您的迴應。 – offthegrass

0

更緊湊有點...

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; 
} 
0

更新

我其實只是在我的陣列中的兩個項目,所以我做了

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

下面的回答也是可行的,如果我有一個更大的數組,我會使用它們。

相關問題