如何获取输入的包含形式? [英] How to get the containing form of an input?
问题描述
当我只有对 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,.form
属性IE 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.
如果这是不同类型的元素(不是 ),您可以使用
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'));
此外,请参阅 HTMLInputElement
的 form
属性上的此 MDN 链接:
Also, see this MDN link on the form
property of HTMLInputElement
:
这篇关于如何获取输入的包含形式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!