javascript 使用浏览器中的javascript按类设置html输入元素的值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20814699/
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-27 19:21:43  来源:igfitidea点击:

set value of html input elements by class with javascript in browser?

javascripthtml

提问by Max Hodges

I need set value of a bunch of input boxes based on class (class="Qty")

我需要根据类(class =“Qty”)设置一堆输入框的值

this works if I use the ElementID

如果我使用 ElementID,这会起作用

document.getElementById('G_Qty_0').value='101'

but this doesn't work

但这不起作用

document.getElementsByClassName('Qty').value='100'

What gives?

是什么赋予了?

Cheers!

干杯!

回答by T.J. Crowder

document.getElementsByClassNamereturns a NodeList, not an individual element. You can loop through the list, e.g.:

document.getElementsByClassName返回 a NodeList,而不是单个元素。您可以遍历列表,例如:

var list = document.getElementsByClassName('Qty');
var n;
for (n = 0; n < list.length; ++n) {
    list[n].value='100';
}

Or if you know there will be only one match (and you knowthere won't be zero matches):

或者,如果您知道只有一场比赛(并且您知道不会有零场比赛):

document.getElementsByClassName('Qty')[0].value = '100';

You might also look at querySelectorand querySelectorAll, because they're actually better-supported than getElementsByClassName(specifically: IE8 supports them, but doesn't have getElementsByClassName). querySelectorlooks for the firstelement in the document that matches the given CSS selector and returns that element instance (or nullif there are none). querySelectorAllreturns a NodeListof all matching elements. (That NodeListis not quite the same as the one returned by getElementsByClassName, in that it's a snapshot as of when you make the call, not a live NodeList).

您也可以查看querySelectorand querySelectorAll,因为它们实际上比getElementsByClassName(特别是:IE8 支持它们,但没有getElementsByClassName)得到更好的支持。querySelector查找文档中与给定 CSS 选择器匹配的第一个元素并返回该元素实例(或者null如果没有)。querySelectorAll返回NodeList所有匹配元素的一个。(这NodeList与 返回的不完全相同getElementsByClassName,因为它是您拨打电话时的快照,而不是实时NodeList)。

So for instance:

所以例如:

document.querySelector('.Qty').value = '100';

Or:

或者:

var list = document.querySelectorAll('.Qty');
var n;
for (n = 0; n < list.length; ++n) {
    list[n].value='100';
}