现在我正在尝试以下代码,但在页面加载时我的任何输入文本框中都不会显示任何内容。
HTML:
<body onload="test()">
<input type="text" id="line0"></input>
<br>
<input type="text" id='line1'></input>
<br>
<input type="text" id='line2'></input>
</body>
使用Javascript:
function test() {
var value = "test|some|thing";
var valueArray = value.split("|");
for (var lineNumber=0; lineNumber < valueArray.size(); lineNumber++)
{
line = "line" + lineNumber;
document.getElementById(line).value = valueArray[lineNumber];
}
}
JFiddle:http://jsfiddle.net/mWL9m/1/
在我的实际代码中,我将从函数外部引入一个值,但这并不重要。现在我只是使用测试值value
。
我看过几个不同的主题,但似乎所有主题都集中在onclick
而不是onload
。
答案 0 :(得分:0)
更新了你的小提琴,这是代码。
(function(){ //This replaces the onload by executing the code within this annonymous function once the page loads.
var value = "test|some|thing"; //No edits here
var lineNumber = 0; //No edits here
var valueArray = value.split("|");
for (lineNumber=0; lineNumber < valueArray.length; lineNumber++) { //using .length instead of size and initialized lineNumber again, mostly because I like to keep my initialization in the loop, personal preference.
var lineid = "line" + lineNumber; // It was missing "var", changed the variable name too
var currentLine = valueArray[lineNumber]; //same deal
var inputElem=document.getElementById(lineid); //I get the element before accessing the value property, again, preference mostly
inputElem.value = currentLine; //same code.
} //End of for loop
})(); //end of the annonymous function
答案 1 :(得分:0)
您使用了错误的属性来获取数组的大小。用户 .length 而不是 .size()。
示例:http://jsfiddle.net/u2g2p/1/
function test() {
var value = "test|some|thing";
var valueArray = value.split("|");
for (var lineNumber=0; lineNumber < valueArray.length; lineNumber++)
{
line = "line" + lineNumber;
document.getElementById(line).value = valueArray[lineNumber];
}
}
答案 2 :(得分:0)
你的小提琴有两个问题。首先,您应该使用length
而不是size()
来获取数组的长度(我不相信Javascript数组有一个内置的大小方法):
for (lineNumber=0; lineNumber < valueArray.length; lineNumber++) {
第二个是因为测试功能的声明范围,它在加载时没有找到。阅读本文:
JavaScript not running on jsfiddle.net
并改变
function test() {
对此:
window.test = function() {
答案 3 :(得分:0)
<script>
document.onreadystatechange = function()
{
Javascript code goes here
}
</script>
或
<script>
window.onload = function()
{
Javascript code goes here
}
</script>
答案 4 :(得分:0)
它是数组中对象数量的.length。
/*Javascript*/
function test(){
var testVal = "test|some|thing";
testValArr = testVal.split('|');
for (i = 0; i < testValArr.length; i++) {
document.getElementById('line' + i).value = testValArr[i];
}
}