为什么这个javascript代码只打印第一个列表条目? [英] Why does this javascript code prints the first list entry only ?
问题描述
我是javascript的初学者。我试图编写一个代码,从文本框中获取用户的输入。我想捕获数组中的输入,所以我在互联网上查找了一种方法。我有一个方法document.getElementsByName(name),它返回具有该名称的所有元素的HTML集合。我编写了一个脚本来使用该功能,但奇怪的是,它只是打印列表中的第一个值。长度函数显示正确的长度,即3,但只打印第一个值。任何帮助,将不胜感激。以下是代码:
I am a beginner in javascript. I was trying to write a code that takes input from the user in textboxes . I wanted to capture the inputs in an array, so i looked up for a method on the internet. I got a method document.getElementsByName("name") that returns an HTML collection of all element with that name. I wrote a script to utilise that function, but strangely, it is just printing only the first value in the list. The length function shows me the correct length, i.e 3 , but only the first value is being printed. Any help would be appreciated. Here is the code:
<html>
<head>
<title>Test</title>
<script type="text/javascript">
function fun(){
var list = document.getElementsByName("array");
document.write(list[0].value+"<br>");
document.write(list[1].value+"<br>");
document.write(list[2].value+"<br>");
}
</script>
</head>
<body>
<input type="text" name="array"><br>
<input type="text" name="array"><br>
<input type="text" name="array"><br>
<input type="button" value="go" onclick="fun()">
</body>
</html>
我尝试过:
我已经尝试逐一打印长度,以及列表中的各个元素。所有这些都有效。但是当我想一次打印所有值时,它只打印第一个值
What I have tried:
I have tried printing the length, as well as individual elements of the list one by one. All of them works. But when i want to print all of the values at once, it just prints the first value
推荐答案
在浏览器中查看错误控制台,你会看到问题:
Check out the error console in your browser, and you'll see the problem:
TypeError: list[1] is undefined
一旦你使用 document.write
,文档的全部内容将替换为您编写的内容。
As soon as you use document.write
, the entire contents of the document are replaced with whatever you've written.
注意:当document.write写入文档流时,在已关闭(加载)的文档上调用document.write会自动调用document.open,这将清除文档。
Note: as document.write writes to the document stream, calling document.write on a closed (loaded) document automatically calls document.open, which will clear the document.
清算文件会破坏其中的元素,因此您无法再读取输入值。
您需要在写入文档之前阅读值:
Clearing the document destroys the elements on it, so you can no longer read the value of the inputs.
You'll need to read the values before writing to the document:
function fun(){
var list = document.getElementsByName("array");
var values = [];
for (var i = 0; i < list.length; i++){
values.push(list[i].value);
}
document.write(values.join("<br />"));
document.close();
}
这是工作的Plunker。当你使用document.write时,它会覆盖以前的值。
Working Plunker [ ^ ]
Hepe this help
Here is the working Plunker. When you use document.write , it will overwrite the previous value.
Working Plunker[^]
Hepe this helps
这篇关于为什么这个javascript代码只打印第一个列表条目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!