1

我在 javascript popUp 中有一个小函数,我想知道 getElementByClassName 函数是否返回一个包含该类的所有元素的数组,而不是为什么当我提醒它说对象 Html 输入元素时,尽管我的表单编号字段中有什么(空白空间或一些数字)。那么我如何从该数组中获取值。

 var arr = document.getElementsByClassName('num');

function popUp(){
    for(var i = 0;i < arr.length;i++){
        alert(arr[i]);
    }
}

这是HTML:

<form id = "matrix">

<input type = "number" class = "num" />
<input type = "number" class = "num" />

<input type = "number" class = "num" />
<input type = "number" class = "num" />

<input type = "button" value = "count" id = "count" onclick = "popUp()"/>
</form>
</div>
4

3 回答 3

2

使用 .value

alert(arr[i].value);

如果你需要兼容 IE8-,你不应该使用

type = "number"

它是 HTML5,IE8 不支持。
请改用 type="text"。

于 2013-04-21T12:00:14.887 回答
1

document.getElementsByClassName()返回一个 DOM 元素的集合,以便arr[i]获取 DOM 元素,而不是元素中的内容。如果您想要来自该 DOM 元素的属性,例如value标签的input,那么您必须引用您想要的属性,例如.value

var arr = document.getElementsByClassName('num');

function popUp(){
    for(var i = 0;i < arr.length;i++){
        alert(arr[i].value);
    }
}
于 2013-04-21T12:03:01.620 回答
0

getElementsByClassName 将返回所有匹配的 html 元素的列表。通过调用 alert(arr[i]),您是在告诉客户端显示元素,而不是其值,这就是为什么警报消息告诉您它是一个 html 输入。要显示元素的值,请使用以下命令

alert(arr[i].value);
于 2013-04-21T12:05:22.637 回答