我有四个按钮,id为button2。
document.getElementById('button2').disabled=true;
使用上面的代码,只有一个按钮被禁用。我希望禁用所有按钮。
任何想法。
谢谢。
最佳答案
I have four buttons with button2 as id.
不要这样做,it's invalid 。 id
值必须在文档中是唯一的。
相反,也许给他们相同的 class
:
<input type="button" class="button2">
<input type="button" class="button2">
<input type="button" class="button2">
<input type="button" class="button2">
然后modern browsers你可以这样做:
var list = document.querySelectorAll(".button2");
var index;
for (index = 0; index < list.length; ++index) {
list[index].disabled = true;
}
这适用于几乎所有内容的当前版本。它不适用于 IE7 及更早版本。如果您需要支持这些,我建议使用一个不错的 DOM 操作库(例如 jQuery 、 YUI 、 Closure 或 any of several others ),它将能够按类查找元素。
<小时/>或者,您可以给他们相同的 name
并使用旧的 getElementsByName
,甚至在 IE6 和 IE7 上也是如此:
<input type="button" name="button2">
<input type="button" name="button2">
<input type="button" name="button2">
<input type="button" name="button2">
然后是同样的循环:
var list = document.getElementsByName("button2");
var index;
for (index = 0; index < list.length; ++index) {
list[index].disabled = true;
}
但是使用name
有一些注意事项为此:
如果这是在
form
中,虽然在这种情况下这样做很好,因为这些是按钮,但您可能不想使用name
对于一般情况来说。如果您使用相同的name
例如,对于多个文本字段或选择框,您必须确保在收到重复的字段名称时在服务器端进行正确的处理。类似地,虽然适合这种用途,
name
仅是表单字段上的有效属性,而不是其他类型的元素。因此,虽然按钮可以接受,但您不想对其进行概括。小心不要使用
"button2"
作为id
在同一页面上,因为 IE8 及更早版本中有一个错误,会使其表现得像该元素具有name
"button2"
尽管事实并非如此。这是我谈论的同一个错误 here与getElementById
相关.
所以一般来说,class
可能是更好的方法。
关于javascript - 使用 javascript 禁用按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18022560/