jQuery 如何从元素中找到父表单?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3603487/
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
How to find parent form from element?
提问by st78
I am trying to find parent form from element using code below:
我正在尝试使用以下代码从元素中查找父表单:
<form id="f1" action="action1.html">
form1 <button id="btn1" onclick="testaction(this); return false;" >test form 1</button>
</form>
<script type="text/javascript" >
function testaction(element) {
var e = $(element.id);
var form = e.parent('form');
alert(form.id); // undefined!!
alert(form.action); // undefined!!
alert(document.forms[0].action); //http://localhost/action1.html
}
</script>
It should be something really simple.... Thanks in advance
这应该是非常简单的事情......提前致谢
采纳答案by Ryley
The problem you're having is that form
is a jQuery object, not a DOM object. If you want it to be the form object, you would do e.parent('form').get(0)
.
您遇到的问题是这form
是一个 jQuery 对象,而不是 DOM 对象。如果你想让它成为表单对象,你会做e.parent('form').get(0)
.
Furthermore, you're treating element incorrectly - jQuery takes id selectors in the form #id
but you've passed it id
.
此外,您错误地对待元素 - jQuery 在表单中采用 id 选择器,#id
但您已经通过了它id
。
Here's a working version:
这是一个工作版本:
function testaction(element) {
var e = $(element);//element not element.id
var form = e.parent('form').get(0);//.get(0) added
alert(form.id); // undefined!!
alert(form.action); // undefined!!
alert(document.forms[0].action); //http://localhost/action1.html
}
See this for it in action: http://jsfiddle.net/BTmwq/
看到它在行动:http: //jsfiddle.net/BTmwq/
EDIT: spelling, clarity
编辑:拼写,清晰度
回答by Angelo R.
http://api.jquery.com/closest/will do it. Used like this
http://api.jquery.com/closest/会这样做。像这样使用
$('#elem').closest('form');
回答by Sergei
Button element has form property http://www.w3schools.com/jsref/dom_obj_pushbutton.asp
按钮元素具有表单属性http://www.w3schools.com/jsref/dom_obj_pushbutton.asp
buttonElement.form
回答by jAndy
Throw the inline event handler aboard and stay unobtrusive here.
将内联事件处理程序扔掉,并在此处保持低调。
$(document).ready(function(){
$('#btn1').bind('click', function(){
var form = $(this).closest('form')[0];
alert(form.id); // defined
alert(form.action); // defined
});
});
Ref.: .closest(), .bind()
参考:.closest(), .bind()
回答by Sruly
$(".whatever").parents("form");