jQuery 查找父表单
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1621714/
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
jQuery find parent form
提问by kmunky
i have this html
我有这个 html
<ul>
<li><form action="#" name="formName"></li>
<li><input type="text" name="someName" /></li>
<li><input type="text" name="someOtherName" /></li>
<li><input type="submit" name="submitButton" value="send"></li>
<li></form></li>
</ul>
How can i select the form that the input[name="submitButton"]
is part of ?
(when i click on the submit button i want to select the form and append some fields in it)
我怎样才能选择属于的表单input[name="submitButton"]
?(当我点击提交按钮时,我想选择表单并在其中附加一些字段)
回答by karim79
回答by peterjwest
You can use the form reference which exists on all inputs, this is much faster than .closest()
(5-10 times faster in Chrome and IE8). Works on IE6 & 7 too.
您可以使用存在于所有输入中的表单引用,这比.closest()
(在 Chrome 和 IE8 中快 5-10 倍)要快得多。也适用于 IE6 和 7。
var input = $('input[type=submit]');
var form = input.length > 0 ? $(input[0].form) : $();
回答by userfuser
To me, this looks like the simplest/fastest:
对我来说,这看起来是最简单/最快的:
$('form input[type=submit]').click(function() { // attach the listener to your button
var yourWantedObjectIsHere = $(this.form); // use the native JS object with `this`
});
回答by Alexander Mihailov
回答by Jonathan Hendler
see also jquery/js -- How do I select the parent form based on which submit button is clicked?
另请参见jquery/js -- 如何根据单击的提交按钮选择父表单?
$('form#myform1').submit(function(e){
e.preventDefault(); //Prevent the normal submission action
var form = this;
// ... Handle form submission
});