javascript 使用 jQuery .submit() 检索提交表单的 ID 和/或名称
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7269811/
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
Retrieve submitted form's ID and/or Name with jQuery .submit()
提问by pnm123
I've loaded few forms using .load() to different DIVs. The loaded file looks like the following example.
我已经使用 .load() 将几个表单加载到不同的 DIV。加载的文件类似于以下示例。
<div id="block_id-299">
<div id="content">
<form name="form1" method="post">
<input type="submit" name="field1" value="Submit">
</form>
</div>
</div>
And now I am trying to retrieve submitted form's name and later, it's values using .serialize()
.
I was using $('form').submit(function(){ ... }
but since I am loading the form dynamically, this does not work anymore.
现在我试图检索提交的表单的名称,稍后,它的值使用.serialize()
. 我正在使用,$('form').submit(function(){ ... }
但由于我正在动态加载表单,因此不再起作用。
Any help?
有什么帮助吗?
PS: The event can be catched using $(document).submit(function(){
but how to get form's name and/or ID?
PS:可以使用$(document).submit(function(){
但如何获取表单的名称和/或 ID来捕获事件?
回答by Arnaud Le Blanc
You can do this with $().delegate:
你可以用 $().delegate 做到这一点:
$(document).delegate('form', 'submit', function(event) {
var $form = $(this);
var id = $form.attr('id');
var data = $form.serialize();
// ...
});
This works even on forms added after you called delegate().
这甚至适用于在调用 delegate() 之后添加的表单。
This works by listening for submit
events the bubbled up to document
, and by testing if the even originates from a form
element.
这通过侦听submit
冒泡到 的事件document
并通过测试偶数是否来自form
元素来工作。
This is similar to $('form').live('click', ...)
, but doesn't initially executes the selector.
这类似于$('form').live('click', ...)
,但最初不执行选择器。
See .delegate()
and .live()
documentation.
请参阅.delegate()
和.live()
文档。
回答by Srinivasan.S
回答by ShankarSangoli
回答by ahmed
Following code will alert the form id of the button having 'create_btn' css, you can also access it by id if you want by changing the (.create-btn)dot to hash(#create-btn) and you can use .click or .submit instead.
以下代码将提醒具有 'create_btn' css 的按钮的表单 id,如果需要,您也可以通过 id 访问它,方法是将 (.create-btn)dot 更改为 hash(#create-btn) 并且您可以使用 .click或 .submit 代替。
<script type="text/javascript">
$(document).ready(function () {
$('.create-btn').click(function(){
alert(this.form.id);
}) ;
});