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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:51:50  来源:igfitidea点击:

jQuery find parent form

jquerytraversal

提问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

I would suggest using closest, which selects the closest matching parent element:

我建议使用closest,它选择最匹配的父元素:

$('input[name="submitButton"]').closest("form");

Instead of filtering by the name, I would do this:

而不是按名称过滤,我会这样做:

$('input[type=submit]').closest("form");

回答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

As of HTML5 browsers one can use inputElement.form- the value of the attribute must be an id of a <form>element in the same document. More info on MDN.

对于可以使用的 HTML5 浏览器inputElement.form,该属性的值必须是<form>同一文档中元素的 id 。有关MDN 的更多信息。

回答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
});