getElementsByName() 不起作用? [英] getElementsByName() not working?

查看:39
本文介绍了getElementsByName() 不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a Javascript function which should update a hidden input field in my form with a number that increments every time the function is called.

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

It worked originally with getElementById() however because I had to redesign my form I cannot use the php function to assign an individual ID to the element so all I have is a unique name for that element.

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

So instead I decided to use getElementsByName() from Javascript to modify the element.

这是该元素的 HTML

Here is the HTML of that element

  <input type="hidden" value="" name="staff_counter">

这是我的 Javascript 代码:

This is my Javascript code:

window.onload=function()
{

//function is activated by a form button 

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


                s++;
}

当函数被调用并且输入字段没有获得给它的值时,我在 Firebug 上没有收到任何错误.

I am getting no errors on Firebug when the function is called and the input field is not getting a value given to it.

它曾与 getElementById() 一起工作,但为什么突然间它不能与 getElementsByName() 一起工作?

It was working with getElementById() but why all of a sudden it does not work with getElementsByName()?

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

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

Here is the code I use from Codeigniter to make the element

// 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'));

谢谢

推荐答案

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

document.getElementsByName() returns a NodeList, so you have to access it by an index: document.getElementsByName('staff_counter')[0] (depending on how many of these you have).

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

You also have access to a length property to check how many Elements were matched.

这篇关于getElementsByName() 不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆