我试图从元素中找到父表单,使用下面的代码:
<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>
它应该是一个非常简单的事情….提前感谢
解决方法
您所遇到的问题是该表单是一个jQuery对象,而不是一个DOM对象。如果你想要它是表单对象,你可以做e.parent(‘form’)。get(0)。
此外,您正在不正确地处理元素 – jQuery以#id的形式使用id选择器,但是您已经通过它的id。
这是一个工作版本:
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
}
看到它在行动:http://jsfiddle.net/BTmwq/
编辑:拼写,清晰