在 Javascript 中检索表单的“名称”属性,而存在名称为“名称”的输入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3937888/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 02:45:02  来源:igfitidea点击:

Retrieve form's "name" attribute in Javascript whereas an input exists with name "name"

javascriptformsdomattributes

提问by Frédéric

I have something like this HTML structure :

我有这样的 HTML 结构:

   <form name="myvalue" id="hello">
      <input type="text" name="name" />
    </form>

I'd like to retrieve the form's name attribute in Javascript, with a cross browser solution.

我想使用跨浏览器解决方案在 Javascript 中检索表单的名称属性。

Obviously,

明显地,

document.getElementById("hello").name 

won't work because it will return the corresponding input object.

不会工作,因为它将返回相应的输入对象。

Under chrome, following code works, but I didn't succeeded to find the equivalent for Internet Explorer 8

在 chrome 下,以下代码有效,但我没有成功找到 Internet Explorer 8 的等效项

document.getElementById("hello").getAttribute("name")

Thanks in advance !

提前致谢 !

Frédéric

弗雷德里克

回答by lincolnk

I think this oughtta work

我认为这应该有效

document.getElementById("hello").attributes["name"].value;

tests ok in IE8, which is all I have. you might have to do some browser checking and pick your approach as needed.

在 IE8 中测试正常,这就是我所拥有的。您可能需要进行一些浏览器检查并根据需要选择您的方法。

edits: actually, your example works fine for me in IE8 too. but not ie7.

编辑:实际上,您的示例在 IE8 中也适用于我。但不是ie7。

回答by Dagg Nabbit

Try this:

试试这个:

function getFormName (formElement) {
  if (!formElement) return;
  var a=formElement.attributes;
  for (var i=a.length; i--;) {
    if (a[i].name=='name') return a[i].value;
  }
}

Not sure if it will work in IE. Should work everywhere else.

不确定它是否适用于 IE。应该在其他地方工作。