getElementsByName()不起作用?

sql*_*ole 17 html javascript codeigniter getelementsbyname

我有一个Javascript函数,它应该更新我的表单中的隐藏输入字段,其中的数字在每次调用函数时递增.

它最初使用getElementById(),但是因为我必须重新设计我的表单,我不能使用php函数为元素分配一个单独的ID,所以我拥有的是该元素的唯一名称.

所以我决定使用Javascript中的getElementsByName()来修改元素.

这是该元素的HTML

  <input type="hidden" value="" name="staff_counter">
Run Code Online (Sandbox Code Playgroud)

这是我的Javascript代码:

window.onload=function()
{

//function is activated by a form button 

var staffbox = document.getElementsByName('staff_counter');
                    staffbox.value = s;


                s++;
}
Run Code Online (Sandbox Code Playgroud)

当调用函数并且输入字段没有获得赋值时,我在Firebug上没有错误.

它正在使用getElementById(),但为什么突然间它不能与getElementsByName()一起使用?

  • - 我已经检查过它是文档中唯一的唯一元素.
  • - 我在激活功能时检查了Firebug上的任何错误

这是我使用Codeigniter制作元素的代码

// staff_counter is name and the set_value function sets the value from what is
//posted so if the validation fails and the page is reloaded the form element does
// not lose its value

echo form_hidden('staff_counter', set_value('staff_counter'));
Run Code Online (Sandbox Code Playgroud)

谢谢

Dig*_*ane 30

document.getElementsByName()返回一个NodeList,因此您必须通过索引访问它:( document.getElementsByName('staff_counter')[0]取决于您拥有多少个).

您还可以访问length属性以检查匹配的元素数量.

  • 它不是**阵列.它是一个[`NodeList`](https://developer.mozilla.org/en-US/docs/Web/API/NodeList#Why_is_NodeList_not_an_Array.3F).很大的区别. (6认同)