2013-10-11 16 views
2

我有以下HTML:如果我只知道該元素的名稱,如何禁用我的頁面上的按鈕?

<button name="darkBlue" onclick="setThemeColor(this.name)">Blue</button> 
<button name="black" onclick="setThemeColor(this.name)">Black</button> 

與此腳本:

if (localStorage.buttonColor) { 
    var themeButtons = document.querySelectorAll(".theme"); 
    for (var button in themeButtons) { 
     themeButtons[buttons].removeAttribute("disabled"); 
    } 
    // I need here to disable the button with the name that matches localstorage name 
} 

我已經有到位的方式從所有按鈕刪除禁用。但我怎麼才能禁用與localStorage.buttonColor同名的按鈕,而不使用jQuery?

我也可以在for (var button in themeButtons)循環中做所有這些嗎?如果我能做到這一點,它可能會更加清潔解決方案。

+2

'document.getElementsByName'? – putvande

回答

5

如果只有一個按鈕:

document.querySelector('button[name="' + localStorage.buttonColor + '"]').disabled = true; 

或者:

var el = document.getElementsByName(localStorage.buttonColor); 
if (el) { 
    el[0].disabled = true; 
} 

如果有多個要素:

var all = document.querySelectorAll('button[name="' + localStorage.buttonColor + '"]'); 
for (var i = 0, len = all.length; i<len; i++){ 
    all[i].disabled = true; 
} 

如果有多個按鈕,你需要啓用那些不分享localStorage.buttonColor名稱的人:

var buttons = document.getElementsByTagName('button'), 
    buttonsQSA = document.querySelectorAll('button'); 

// iterate over whichever collection you prefer to use 
for (var i = 0, len = buttonsQSA.length; i<len; i++){ 
    buttonsQSA[i].disabled = buttonsQSA[i].name == localStorage.buttonColor; 
} 
+0

大衛你好。你能解釋一下你的兩個答案之間的區別,並讓我知道一個人是否可能比另一個人好。有多個按鈕。只有一個(只有一個)名稱與本地存儲相匹配需要禁用。其他人需要「禁用」刪除。希望這是有道理的。 – Melina

+0

'document.querySelector()'需要一個現代/最新的瀏覽器(但你已經在使用'.querySelectorAll()',它具有完全相同的需求),並且這隻會檢索一個元素(第一個匹配它找到)。後一種方法將檢索該名稱的所有元素(不管元素類型如何),但不具體,但迄今爲止,跨瀏覽器兼容性更好。 –

+0

非常感謝。我會在7分鐘內接受。 – Melina

相關問題