Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/390.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用javascript禁用按钮_Javascript - Fatal编程技术网

使用javascript禁用按钮

使用javascript禁用按钮,javascript,Javascript,我有四个按钮,按钮2作为id。 document.getElementById('button2')。disabled=true 使用上述代码,只有一个按钮被禁用。我想禁用所有按钮。 任何想法。 多谢各位 我有四个按钮,按钮2作为id 不要那样做id值在文档中必须是唯一的 相反,可能给他们相同的类: <input type="button" class="button2"> <input type="button" class="button2"> <input t

我有四个按钮,按钮2作为id。

document.getElementById('button2')。disabled=true

使用上述代码,只有一个按钮被禁用。我想禁用所有按钮。
任何想法。
多谢各位

我有四个按钮,按钮2作为id

不要那样做<代码>id值在文档中必须是唯一的

相反,可能给他们相同的

<input type="button" class="button2">
<input type="button" class="button2">
<input type="button" class="button2">
<input type="button" class="button2">
然后大致相同的循环:

var list = document.getElementsByName("button2");
var index;
for (index = 0; index < list.length; ++index) {
    list[index].disabled = true;
}
var list=document.getElementsByName(“button2”);
var指数;
对于(索引=0;索引
但是使用
name
有几个注意事项:

  • 如果这是一个
    表单
    ,虽然在这种情况下可以这样做,因为它们是按钮,但在一般情况下,您可能不想使用
    名称
    。例如,如果对多个文本字段或选择框使用相同的
    名称
    ,则必须确保在收到重复的字段名称时在服务器端正确处理该名称

  • 类似地,尽管可以使用,
    name
    只是表单字段上的有效属性,而不是其他类型的元素。同样,虽然按钮还可以,但你不想概括它

  • 小心不要在同一页上使用
    “button2”
    作为
    id
    ,因为IE8和更早版本中有一个bug,这会使它看起来像元素有
    名称
    “button2”
    ,即使它没有。这和我在
    getElementById
    中提到的bug是一样的


  • 因此,一般来说,
    class
    可能是更好的方法。

    一个页面上应该只出现一个id值。为每个按钮使用不同的id值(例如,一个按钮使用id=“button1”,另一个按钮使用id=“button2”)

    然后可以禁用每个按钮,一次禁用一个:

    document.getElementById('button1').disabled=true;
    document.getElementById('button2').disabled=true;
    

    ID是标识符的缩写。您每页只能使用一次,或者您必须期望它不能按预期工作。您应该为不同的元素使用不同的ID。或者,使用一个类并通过
    getElementsByClassName
    检索元素。我有四个按钮,按钮2是ID。这就是您的问题,
    ID
    s应该不是o保持唯一性(例如,每个元素一个)。您可以对
    name
    属性执行相同的操作,然后
    getElementsByName
    这是正确的答案。@abc123:是的,当您删除您的答案时,我正在评论它(说“@theotheruser这是
    name
    完全可以接受的用例”)问你:
    getElementsByName
    的支持是什么样的?它在所有浏览器中都可用,甚至从5.5@abc123:是的,只是在试验。遗憾的是,它在IE8和早期版本(the)中被破坏了,但是可以通过避免对名称和ID使用相同的字符串来解决:()。@talemyn:按钮也可以(因为它们不是与表单一起提交的;如果它们是提交按钮,则只有实际单击的按钮才会与表单一起提交)。您完全正确,对于文本字段来说,这是不好的,除非您希望在服务器端正确处理它(很多人都是这样做的;接收多个同名字段并不少见)。
    var list = document.getElementsByName("button2");
    var index;
    for (index = 0; index < list.length; ++index) {
        list[index].disabled = true;
    }
    
    document.getElementById('button1').disabled=true;
    document.getElementById('button2').disabled=true;