javascript jQuery 等效于 document.forms[0].elements[i].value; 是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3285630/
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
What is the jQuery equivalent to document.forms[0].elements[i].value;?
提问by Ian
What is the jquery equivalent to: document.forms[0].elements[i].value;?
jquery 相当于什么:document.forms[0].elements[i].value;?
I don't know how to travel through a form and its elements in jQuery and would like to know how to do it.
我不知道如何在 jQuery 中遍历表单及其元素,并且想知道如何去做。
回答by Nick Craver
The usual translation is the :inputselector:
通常的翻译是:input选择器:
$("form:first :input").each(function() {
alert($(this).val()); //alerts the value
});
The :firstis because your example pulls the first <form>, if there's only one or you want all input elements, just take the :firstoff. The :inputselectorworks for <input>, <select>, <textarea>...all the elements you typically care about here.
这:first是因为您的示例拉取了第一个<form>,如果只有一个或者您想要所有输入元素,请:first关闭。在:input选择工程<input>,<select>,<textarea>...所有的元素,你通常关心这里。
However, if we knew exactly what your goal is, there's probably a very simple way to achieve it. If you can post more info, like the HTML and what values you want to extract (or do something else with).
但是,如果我们确切地知道您的目标是什么,那么可能有一种非常简单的方法来实现它。如果您可以发布更多信息,例如 HTML 以及您想要提取的值(或执行其他操作)。
回答by Fortes
Well, translated literally, it'd be:
好吧,从字面上翻译,它会是:
$('form:first *:nth-child(i)').val()
But jQuery makes it easy to grab elements by other manners such as ID or CSS selector. It'd be easier to maintain if you did something like:
但是 jQuery 可以很容易地通过其他方式(例如 ID 或 CSS 选择器)获取元素。如果您执行以下操作,则维护起来会更容易:
$('form#id input.name').val()
回答by spinon
This will give you all elements under the form. Including non form elements:
这将为您提供表单下的所有元素。包括非表单元素:
$("#[form id]").find()
Then you can use an each function to traverse all the children. Or you can use the input selector to only return the form elements:
然后你可以使用 each 函数来遍历所有的孩子。或者您可以使用输入选择器仅返回表单元素:
$("#[form id] :input")
回答by Matthew J Morrison
I'm not exactly sure what you're trying to accomplish, but you should be able to do something like this:
我不确定您要完成什么,但您应该能够执行以下操作:
$('form:first').children(':first').val();
This will get the value of the first child node within the first <form>tag in the DOM.
这将获得<form>DOM 中第一个标签内的第一个子节点的值。
回答by Luis Junior
$("#formid input").each(function(){
alert($(this).attr("value"))
})

