在Jquery中选择给定表单的所有输入 [英] Select all inputs of a given form in Jquery

查看:73
本文介绍了在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.

这篇关于在Jquery中选择给定表单的所有输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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