javascript 如何通过将 $(this).parent() 与 JQuery 一起使用来序列化当前 div?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3644342/
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
How to serialize current div by using $(this).parent() with JQuery?
提问by Sam Stoelinga
I am trying to serialize the current div by using a clickevent. See code for good explanation:
我正在尝试使用 clickevent 序列化当前 div。请参阅代码以获得很好的解释:
$("#createreview").live('click', function() {
alert($(this).parent().serialize());
$.post('/admin/home/review/create/', $(this).parent().serialize(), function(data){
alert('Review succesfully added to database.' +data);
});
});
Alert will show nothing, which means the div is not being serialized. This is the html in question. It's inside a dialog, which is also the reason why i have to use live().
Alert 不会显示任何内容,这意味着 div 没有被序列化。这是有问题的html。它在一个对话框中,这也是我必须使用 live() 的原因。
<div id="reviewdiv">
<input type="hidden" value="7" name="homeid">
<label>Content</label><textarea name="reviewcontent" id="reviews" rows="3" cols="60"></textarea><br>
<label>Author</label> <input type="text" name="reviewauthor"><button class="ui-state-default ui-corner-all" id="createreview">Save Review</button><button class="ui-state-default ui-corner-all" id="removereview">Remove Review</button><br>
</div>
Also this code is working without a problem to remove the current div by using the clickevent and parent selector.
此外,此代码在使用 clickevent 和父选择器删除当前 div 时没有问题。
$("#removereview").live('click', function() {
$(this).parent().slideUp();
});
回答by JCM
You can serialize a <div>.
您可以序列化一个<div>.
The serializeuses internally the parammethod. So to serialize input elements that do not belong to a form, use the parammethod. Example: http://jsfiddle.net/DdVqJ/
所述序列化在内部使用param方法。因此,要序列化不属于表单的输入元素,请使用该param方法。示例:http: //jsfiddle.net/DdVqJ/
But remember, the correct (and semantic) way is to put your input elements inside a form.
但请记住,正确(和语义)的方法是将您的输入元素放在表单中。
回答by Nick Craver
You can't serialize a <div>, you need to have a <form>, so replace this:
你不能序列化 a <div>,你需要有一个<form>,所以替换这个:
<div id="reviewdiv">
With this:
有了这个:
<form id="reviewdiv">
Then you can use this to serialize:
然后你可以使用它来序列化:
$(this).closest('form').serialize()
To see the difference here's what you have(a <div>) which doesn'tserialize and here's the <form>versionwhich doesserialize. Because it uses the form.elementscollection to loop through, nothing but a <form>works here.
要查看这里的差异,您可以看到(a <div>)没有序列化, 这是序列化的<form>版本。因为它使用集合来循环,所以这里只能使用 a 。form.elements<form>
回答by user2010212
I know this is an old post, but you could just use:
我知道这是一篇旧帖子,但您可以使用:
$('#reviewdiv :input').serialize();

