在Jquery中选择给定表单的所有输入
我在jquery中有一个表单对象,我想选择此表单的所有输入.
I have a form object in jquery, and I'd like to select all inputs of this form.
假设我的表单对象称为 form .如果表单有ID,我就可以
Let's suppose my form object is called form. If the form has an id, I can just do
var id = form.attr('id');
var inputs = $('#' + id + ' input');
如果没有,我可以检查一下,然后手动添加一个临时ID,进行选择,然后删除该ID(或仅将其保留在此处).但这看起来太复杂了,必须有一种更简单的方法,但是我找不到它.
If not I can check this, and then manually add a temporary id, do the selection, and remove the id (or just leave it there). But this just looks too complicated, there must be an easier way, but I'm not able to find it.
另一种可能的方式(我无法工作)类似于
Another possible way (which I'm not able to make work) would be something like
var inputs = $('input').filter(function() {
var parents = this.parents();
return ($.inArray(form, parents) != -1);
});
但是这看起来也很复杂(并且无法按规定进行操作).
but this too seems complicated (and it doesn't work as stated).
从性能的角度来看,哪种方法会更方便?
By the way, from the performance point of view, which approach would be more convenient?
http://docs.jquery .com/Traversing/find
form.find('input')
应该做到我想的窍门.以防万一,如果您试图获取所有输入字段以获取其当前值并使用AJAX提交,则可以使用.
should do the trick I would think. Just in case, if you're trying to get all of the input fields to grab their current values and submit them with AJAX you can just use the .serialize method of your form:
data: form.serialize(),
就您的性能问题而言,我相信您的第一种方法更有效,第二种将遍历页面上的每个输入.从jQuery 1.4开始,第一种方法肯定更有效,基于对象ID的查询最初得到了显着增强.
As far as your performance question goes, I believe your first method is more effecient, the second will iterate over every input on the page. As of jQuery 1.4 the first method is definitely more efficient, querying based off of object IDs initially has been significantly enhanced.