javascript 在Javascript中使用类名禁用文本框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29532597/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 10:41:23  来源:igfitidea点击:

Disable text box using class name in Javascript

javascriptgetelementsbyclassname

提问by Deepu Sasidharan

I have HTML

我有HTML

Name 1:<input type="text" class="one" id="mytext">
<button onclick="disfunction()"></button>

Javascript

Javascript

function disfunction(){
document.getElementsByClassName("one").disabled = true;
}

But the text box is still enabled. How can I disabletext boxusing the classnamein JAVASCRIPT.

但文本框仍处于启用状态。如何禁用JAVASCRIPT 中text box使用类名

Using id I can do this. Also using jquery.

使用 id 我可以做到这一点。也使用jquery。

But I need a solution using Javascriptand classname.

但我需要一个使用Javascriptand的解决方案classname

回答by jmgross

getElementsByClassNamereturn a list of elements, you need to loop througth it to disable each element :

getElementsByClassName返回一个元素列表,您需要遍历它以禁用每个元素:

var cells = table.getElementsByClassName("one"); 
for (var i = 0; i < cells.length; i++) { 
    cells[i].disabled = true;
}

JSFIDDLE : http://jsfiddle.net/7L14zaha/1/

JSFIDDLE:http: //jsfiddle.net/7L14zaha/1/

回答by Eric T

You may try this, and I bet is what you are looking at.

你可以试试这个,我敢打赌这就是你所看到的。

function disfunction(){
document.getElementsByClassName("one")[0].disabled = true;
}

JSFiddle :- Disable on click.

JSFiddle :-禁用点击。

回答by venox

Mozilla docsstates that:

Mozilla文档指出:

elements is a live HTMLCollection of found elements.

元素是已找到元素的实时 HTMLCollection。

So you have to iterate through the result of getElementsByClassName.

所以你必须遍历 getElementsByClassName 的结果。

var testElements = document.getElementsByClassName('class-name-here');
var testDivs = Array.prototype.filter.call(testElements, function(testElement){
    testElement.disabled = true;
});