我有以下 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
}
我已经有办法从所有按钮中移除禁用功能。但是我怎样才能在不使用 jQuery 的情况下禁用与 localStorage.buttonColor 同名的按钮呢?
我还可以在 for (var button in themeButtons)
循环中完成所有这些吗?如果我能做到这一点,它可能是一个更干净的解决方案。
最佳答案
如果只有一个按钮:
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;
}
关于javascript - 如果我只知道该元素的名称,如何禁用页面上的按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19315793/