2010-08-30 42 views
18

我想從下面元素使用代碼找到父窗體:如何從元素中查找父窗體?

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

它應該是很簡單的東西....在此先感謝

+2

'.parent'只給是直系祖先。 – 2010-08-30 19:22:21

+3

您應該只是'$(element)'而不是'$(element.id)'。 – kennytm 2010-08-30 19:23:05

+0

'btn1.form'怎麼樣? – Sergei 2015-10-28 17:07:28

回答

12

您遇到的問題是,form是一個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/

編輯:拼寫,清晰

+0

在這裏,變量'form'應該是'undefined'。 @jAndy的解決方案工作。 – Roland 2018-01-22 16:25:08

38

http://api.jquery.com/closest/將做到這一點。這樣使用

$('#elem').closest('form'); 
+4

最好的解決方案,不像父母(),一旦發現匹配就停下來 – 2010-12-16 19:20:02

+0

「btn1.form」最棒嗎? – Sergei 2015-10-28 17:05:35

0
$(".whatever").parents("form"); 
+3

nearest()是一個好得多的解決方案,因爲一旦找到匹配就停止 – 2010-12-16 19:20:55

6

船上扔聯事件處理程序,並保持不顯眼的位置。

$(document).ready(function(){ 
    $('#btn1').bind('click', function(){ 
     var form = $(this).closest('form')[0]; 

     alert(form.id); // defined 
     alert(form.action); // defined 
    }); 
}); 

參考:.closest().bind()

+0

'nearest(「form」)[0]'是正確的解決方案,返回一個正確的元素。 'parent('form')。get(0)'returned'undefined'! – Roland 2018-01-22 16:16:05

相關問題