jQuery 从表元素而不是整个表单序列化
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7582156/
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
serialize from a table element and not the whole form
提问by Christian
Trying to serialize just the elements from a specific table but it only returns a result if i do the whole Form
尝试仅序列化特定表中的元素,但只有在我完成整个过程时才返回结果 Form
in the below code, i want to ajax just the elements in tbl2
在下面的代码中,我只想对 tbl2 中的元素进行 ajax
<form>
<input type="text" id="tb1" name="tbl1"/>
<table name="tbl1">
<tr><td><input type="text" name="tb2"/></td></tr>
</table>
<table name="tbl2">
<tr><td><input type="text" name="tb3"/></td></tr>
<tr><td><input type="text" name="tb4"/></td></tr>
</table>
</form>
the code
编码
var params = $("#tbl2").serialize();
var resp = $.ajax({
async: false,
type: "POST",
url: AppRoot + "webhandlers/postback.ashx",
data: params
});
回答by kapa
First and foremost, a <table>
cannot have a name
attribute, and even if it could, the jQuery ID selector(#
) would not match it.
首先, a<table>
不能有一个name
属性,即使有,jQuery ID 选择器( #
) 也不会匹配它。
If you use id
instead (<table id="tbl2">
), it will work like this:
如果你id
改用 ( <table id="tbl2">
),它会像这样工作:
var params = $("#tbl2 :input").serialize();
The :input
selector selects all the form elements (here, inside #tbl2
), it is needed because serialize()
will only work on those.
该:input
选择器选择所有的表单元素(在这里,里面#tbl2
),这是必要的,因为serialize()
只会对那些工作。
Please also check out my jsFiddle Demo.
另请查看我的jsFiddle Demo。
回答by Igor Serebryany
you cannot serialize
a table -- that method doesn't apply to that kind of DOM object, only forms and form fields can be serialized.
你不能serialize
是表格——该方法不适用于那种 DOM 对象,只有表单和表单字段可以序列化。
if you really want to do what you're proposing, you need the proper selector to pick just the children of tbl2
that are also form elements, and then you'll have to serialize each one of those by hand. someone did it in another question, here: serialize without a form?
如果你真的想做你提议的事情,你需要正确的选择器来选择tbl2
那些也是表单元素的子元素,然后你必须手动序列化每个元素。有人在另一个问题中做到了,在这里:serialize without a form?
a better way might be to disable all the form elements that are NOT in the table you're interested in -- you'll need a selector to pick all form elements that are not child elements of tbl2
-- and THEN serialize the form. the disabled elements will be omitted.
更好的方法可能是禁用所有不在您感兴趣的表格中的表单元素——您需要一个选择器来选择所有不是其子元素的表单元素tbl2
——然后序列化表单。禁用的元素将被省略。
回答by Jayendra
you can use the serializeArray method, which will give you the array of input fields and can be used with the data.
您可以使用 serializeArray 方法,该方法将为您提供输入字段数组并可与数据一起使用。
var params = $("#tbl2 input").serializeArray();