getElementById值无效

时间:2013-06-07 18:25:57

标签: javascript html getelementbyid

我正在尝试将值从javascript传递到表单上的字段。但是,它似乎不起作用。 html代码是:

<html>
  <head>
     <title>Insert title here</title>
  </head>
  <body onload="splitter()">
    <p>Are you sure you want to delete?</p>
    <form name="myform" action="http://localhost:8080/EfsiDatabase/timer"
          method="post">
      <input type="hidden" name="action" value="delete">
      <input type="hidden" name="index" id="index">
      <input type="submit" name="submit" value="Delete">
    </form>
  </body>
</html>

在javascript文件上,我遇到的问题是我尝试将值分配给索引输入字段的最后一行。我这样做时没有值返回。

<script type="text/javascript">
function splitter() 
{
    var str=window.location.search;
    var replaced=str.replace("?entry=","");
    var n=replaced.split("&entry=");
    var i=0;
    var form = document.forms['myform'];
    while(n)
    {
       var x=n[i].split("%7C%7C");

       var e1 = document.createElement("input");
       e1.type = "hidden";
       e1.name = "staff"+i;
       e1.value = x[0];
       var e2 = document.createElement("input");
       e2.type = "hidden";
       e2.name = "date"+i;
       e2.value = x[1];
       var e3 = document.createElement("input");
       e3.type = "hidden";
       e3.name = "project"+i;
       e3.value = x[2];
       var e4 = document.createElement("input");
       e4.type = "hidden";
       e4.name = "task"+i;
       e4.value = x[3];
       var e5 = document.createElement("input");
       e5.type = "hidden";
       e5.name = "notes"+i;
       e5.value = x[4];
       var e6 = document.createElement("input");
       e6.type = "hidden";
       e6.name = "hours"+i;
       e6.value = x[5];

       form.appendChild(e1);
       form.appendChild(e2);
       form.appendChild(e3);
       form.appendChild(e4);
       form.appendChild(e5);
       form.appendChild(e6);
       i++;
    }
    document.getElementById("index").value=i+1;
}
</script>

如何使用此方法获取值?谢谢你的帮助。

1 个答案:

答案 0 :(得分:3)

而不是

while(n)
{
    var x=n[i].split("%7C%7C");
    // ...
}

请使用以下代码:

while(n[i])
{
    var x=n[i].split("%7C%7C");
    // ...
}