我正在编写基于分隔符(,)拆分数组的javascript,并将该值放入文本框。每个数组包含五个逗号分隔的精确值。我尝试了以下代码并收到错误
“错误:对象不支持此属性或方法”。
我在此网站中找到了与此错误相关的信息,但似乎它不适用于此上下文。请任何人帮我解决这个问题。
<script>
function show() {
var mycars = new Array();
mycars[0] = "768,232,574,768.234";
mycars[1] = "abc, def, ghi, jkl,mno";
for(var i=0; i<mycars[i].length; i++){
mycars= mycars.split(",");
document.getElementById('name')[0].value=mycars;
}
}
</script>
<form>
<table class="cmn-table" id="t1" border="1"
style="margin-left: 0.2em; margin-right: 0em">
<tr>
<th>Sl.No</th>
<th>IP</th>
<th>DP</th>
<th>TCP</th>
<th>SD</th>
<th>ED</th>
</tr>
<tr>
<td><input type="text" name="name11" id="s1" value="1" size="2"
readonly="readonly" /></td>
<td><input type="text" name="name0" id="name" size="20">
</td>
<td><input type="text" name="name1" id="name1" size="20">
</td>
<td><input type="text" name="name2" id="name2" size="20">
</td>
<td><input type="text" name="name3" id="name3" size="15">
</td>
<td><input type="text" name="name4" id="name4" size="15">
</td>
</tr>
<tr>
<td><input type="text" name="name0" id="s2" size="2" value="2"
readonly="readonly" /></td>
<td><input type="text" name="name" id="name5" size="20">
</td>
<td><input type="text" name="name1" id="name6" size="20">
</td>
<td><input type="text" name="name2" id="name7" size="20">
</td>
<td><input type="text" name="name3" id="name8" size="15">
</td>
<td><input type="text" name="name4" id="name9" size="15">
</td>
</tr>
</table>
</form>
<input type="button" value="Click" onclick="show()">
答案 0 :(得分:1)
您必须对HTML进行一处小改动(将“name”的ID更改为“name0”)并使用此JavaScript:
function show() {
var mycars = new Array();
var counter = 0;
mycars[0] = "768,232,574,768,234";
mycars[1] = "abc, def, ghi, jkl,mno";
for (var i = 0; i < mycars.length; i++) {
foo = mycars[i].split(",");
for (var j = 0; j < foo.length; j++) {
document.getElementById('name' + counter).value = foo[j];
counter++;
}
}
}
<强> jsFiddle example 强>
请注意,我假设您的示例mycars[0] = "768,232,574,768.234";
中有拼写错误且应该为mycars[0] = "768,232,574,768,234";