jQuery jquery通过输入id获取表单id

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2532808/
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 13:43:26  来源:igfitidea点击:

jquery get form id by input id

jqueryforms

提问by Mikk

I have really basic question. How can I get form id by input element id.

我有非常基本的问题。如何通过输入元素 id 获取表单 id。

<form id="my_form">
    <fieldset>
        <!--some <div>'s-->
            <input id="my_input"></div>
        <!--some <div>'s end-->
    </fieldset>
</form>

Now if I have

现在如果我有

var form_input = $('#my_input');

How can I get id "my_form"?

我怎样才能得到id“my_form”?

Thank you.

谢谢你。

回答by nickf

Use closest. It searches up the ancestors* of an element to find the first (closest) match.

使用closest. 它搜索元素的祖先*以找到第一个(最接近的)匹配项。

$('#my_input').closest('form').attr('id');

*Note: closest() searches upwards starting with the current element, therefore it can match the current element.

*注意:closest() 从当前元素开始向上搜索,因此它可以匹配当前元素。

回答by Gareth

You don't even need jQuery for this. Every form element has a .form attribute you can use to directly access the form object without needing jQuery's iterative search:

为此,您甚至不需要 jQuery。每个表单元素都有一个 .form 属性,您可以使用它直接访问表单对象,而无需 jQuery 的迭代搜索:

$('#my_input').get(0).form.id

回答by cletus

The simplest method is to use closest():

最简单的方法是使用closest()

var id = $('#my_input').closest('form').attr('id');