jQuery 获取表单的 ID?

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

Get the ID of a form?

jqueryclosest

提问by Roland

I'm using the following code to attach an event to the submit button of a form :

我正在使用以下代码将事件附加到表单的提交按钮:

$('form.manage-users-form').on('click','button.special',function() {

    if ($(this).hasClass('selected')){
        console.log('This user is already special');
    } else {

        $(this).parent().find('button').removeClass('selected');
        $(this).addClass('selected');

        var user_id = $(this).closest("form[id]").val();

        console.log('This user is now special');
        console.log(user_id);
    }
    return false;
});

And you can see that I'm also trying to get the id of the form, but when I check the console I get (an empty string). Why is that and how can I properly get the ID of the form ?

你可以看到我也在尝试获取表单的 id,但是当我检查控制台时,我得到了(an empty string). 为什么会这样,我如何才能正确获取表单的 ID?

回答by vdeantoni

Have you tried?

你有没有尝试过?

var user_id = $(this).closest("form").attr('id');

The id of the element is an attribute, you can extract any attribute (including the id) using .attr().

元素的 id 是一个属性,您可以使用 .attr() 提取任何属性(包括 id)。

.val() is used to extract the value of the element, which makes no sense in a form.

.val() 用于提取元素的值,这在表单中没有意义。

More Info:

更多信息:

.val()
.attr()

.val()
.attr()

回答by Milan

Try this instead. Assuming there is a Single Form on the Page.

试试这个。假设页面上只有一个表单。

 var formid = $('form').attr('id');

Will help you out.

会帮你解决的。

回答by Didier Ghys

.val()is used to get value of form elements, not attribute.

.val()用于获取表单元素的值,而不是属性。

Use .attr():

使用.attr()

var user_id = $(this).closest("form[id]").attr('id');

You can also extractthe DOMElement and use pure javascript to get the ID:

您还可以提取DOMElement 并使用纯 javascript 获取 ID:

var user_id = $(this).closest("form[id]")[0].id;

回答by Bogdan Emil Mariesan

Try the following:

请尝试以下操作:

  var user_id = $(this).closest("form").attr("id");

Will be back with an edit as soon as i test this.

我一测试就回来编辑。