如何获得输入的表单父项? [英] How to get the form parent of an input?

查看:115
本文介绍了如何获得输入的表单父项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我只有一个INPUT的引用时,我需要获得对INPUT的FORM父代的引用。这是可能的JavaScript?

 函数doSomething(element){
//元素是输入对象
//如何获取表单的引用?
}

这行不通:

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

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


解决方案

输入的原生DOM元素也有一个 form 属性指向它们所属的表单:

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

根据 w3schools ,输入字段的 .form 属性由IE 4.0+,Firefox 1.0+,Opera 9.0+支持,如果这是一个不同类型的元素(不是< input>),那么你应该坚持这样做。

; ),你可以找到最接近的父母,它的 最接近

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

另请参阅表格 HTMLInputElement 的属性:




  • https://developer.mozilla.org/en/DOM/HTMLInputElement#Properties

  • ul>

    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?
    }
    

    This doesn't work:

    var form = $(element).parents('form:first');
    
    alert($(form).attr("name"));
    

    解决方案

    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'));
    

    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.

    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'));
    

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

    这篇关于如何获得输入的表单父项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆