如何获取表单ID属性位于

时间:2015-05-13 07:41:58

标签: javascript jquery html

我有以下表格:

<form id="formId">
    <!-- some tags -->
    <div>
        <!-- some other divs or something else -->
            <input type="radio" onclick="handler(this) />
    </div>
</form>

函数处理程序如下所示:

var handler = function(elem){
    init();
    var clicked = //here should be form id
    //other staff
};

如何获取随附表单的ID?假设网页上只有一个表单。

我正在寻找pure-js和jQuery解决方案。

4 个答案:

答案 0 :(得分:5)

你需要:

1)为elem创建jquery对象。

2)使用.closest('form')

遍历表单元素

3)使用.attr('id')获取ID

$(elem).closest('form').attr('id');//will return "formId" in defined click handler

<强> Working Demo

答案 1 :(得分:4)

纯JS解决方案:

var handler = function(elem) {
  // init();
  var clicked = elem.form.getAttribute('id');

  alert(clicked);
};
<form id="formId">
  <!-- some tags -->
  <div>
    <!-- some other divs or something else -->
    <input type="radio" onclick="handler(this)" />
  </div>
</form>

答案 2 :(得分:1)

表单中的每个<input>元素都有一个.form property,其中包含它们所在的<form>元素; .id是任何元素的属性。

&#13;
&#13;
var handler = function(elem) {
  var clicked = elem.form.id;

  alert(clicked);
};
&#13;
<form id="formId">
    <!-- some tags -->
    <div>
        <!-- some other divs or something else -->
            <input type="radio" onclick="handler(this)" />
    </div>
</form>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

你可以像这样制作真正令人讨厌的代码。

var handler = function(elem){
    init();
    var searching = true;
    var tempElem = elem;
    while(searching)
    {
        //added check to make sure there is a parentNode as suggested by @Patrick Roberts
        tempElem = tempElem.parentNode || false;
        if(tempElem)
        {
            //added to lower case as corrected by @Patrick Roberts
            if(tempElem.nodeName.toLowerCase() == "form")conversion
                searching = false;
        }
        else
            searching = false;//EDIT: if there is no form node then it will also stop searching
    }
    formElem = tempElem || {"id" :"no form found"};
    var clicked = formElem.id;//here should be form id
    //other staff
};

基本上创建一个while循环来继续向上移动元素链,直到找到一个表单元素