Javascript w3c document.forms[0].fieldname 等效
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2810573/
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
w3c document.forms[0].fieldname equivalent
提问by Amien
I've been using
我一直在用
document.forms[0].fieldname.value
to get values in javascript from a form, but I'd like to use a name to reference the field and not a 0, what would be the equivalent these days since <form name="formname">isn't compliant?
要从表单中获取 javascript 中的值,但我想使用名称来引用该字段而不是 0,那么由于<form name="formname">不合规,这些天的等效项是什么?
采纳答案by rochal
The easiest way is to add an id to the input: <input id="fieldname" />and reference the value from JavaScript like so:
最简单的方法是在 input: 中添加一个 id:<input id="fieldname" />并从 JavaScript 中引用该值,如下所示:
document.getElementById('fieldname').value
or, if you're using jQuery
或者,如果您使用 jQuery
$('#fieldname').val();
回答by Quentin
The forms collectionis standard DOM 1, there is nothing wrong with using it.
该形式的集合是标准的DOM 1,没有什么错误使用它。
document.forms.formId.elements.field
回答by Braedon King
Would giving the form a name= value and referring to it in the document.forms 'array' by name work?
会给表单一个 name= 值并在 document.forms 'array' 中按名称引用它吗?
i.e.: (much abbreviated)
即:(非常缩写)
<form name="form1">.insert.your.elements.here.with.name.attribute.set.</form>
and in JS:
在 JS 中:
document.forms["form1"]["form_item_name"].value;
I'm a rank amateur so if this is wrong, pls leave me a constructive criticism... :-)
我是一名业余爱好者,所以如果这是错误的,请给我一个建设性的批评...... :-)
回答by kennytm
(document.formsis still supported. You can keep it.)
(document.forms仍受支持。您可以保留它。)
The best way to to give the field an idand use document.getElementById.
给字段一个id和使用的最好方法document.getElementById。
<input type="text" name="fooName" id="fooId" />
...
document.getElementById("fooId").value;
If you can't add an id, you can still use document.getElementsByName, but it will return an array instead of a single element because many may share the same name.
如果您不能添加id,您仍然可以使用document.getElementsByName,但它将返回一个数组而不是单个元素,因为许多可能共享相同的名称。
document.getElementsByName("fooName")[0].value;
回答by Darin Dimitrov
Giving each element an unique id and using this id with the getElementByIdfunction is recommended:
推荐给每个元素一个唯一的 id 并使用这个 id 和getElementById函数:
var value = document.getElementById('idofelement').value;

