如何获得输入的包含形式?

问题描述:

当我仅具有对该INPUT的引用时,我需要获得对该INPUT的FORM父级的引用. JavaScript可以做到这一点吗?如果愿意,可以使用jQuery.

I need to get a reference to the FORM parent of an INPUT when I only have a reference to that INPUT. Is this possible with JavaScript? Use jQuery if you like.

function doSomething(element) {
    //element is input object
    //how to get reference to form?
}

这不起作用:

var form = $(element).parents('form:first');

alert($(form).attr("name"));

作为输入的本地DOM元素还具有form属性,该属性指向它们所属的形式:

Native DOM elements that are inputs also have a form attribute that points to the form they belong to:

var form = element.form;
alert($(form).attr('name'));

根据 w3schools ,IE支持输入字段的.form属性4.0以上版本,Firefox 1.0以上版本,Opera 9.0以上版本,这是jQuery保证的更多浏览器,因此您应该坚持使用.

According to w3schools, the .form property of input fields is supported by IE 4.0+, Firefox 1.0+, Opera 9.0+, which is even more browsers that jQuery guarantees, so you should stick to this.

如果这是不同类型的元素(不是<input>),则可以使用 closest :

If this were a different type of element (not an <input>), you could find the closest parent with closest:

var $form = $(element).closest('form');
alert($form.attr('name'));

此外,请参见HTMLInputElementform属性上的此MDN链接:

Also, see this MDN link on the form property of HTMLInputElement: