2013-05-14 59 views
0

我是一名編程新手,目前我正在學習JQuery。我有一個問題,如果我在列屬性中有一個按鈕,並且當我單擊該屬性的單元格中的按鈕時,我想查找該單元格的唯一標識的值是多少,例如,如果我的屬性名稱被批准值我通過按鈕單擊在「是」和「否」之間切換,我想要在JQuery中獲取唯一的id say name屬性的值,以便我可以使用AJAX調用更新批准的值。在jquery中查找單元格的行

<table> 
<th>S.no</th> 
<th>Name</th> 
<th>Submitted by</th> 
<th>Approved</th> 
<tr> 
<td>1.</td> 
<td>XYZ</td> 
<td>21-3-04</td> 
<td>NO <input type = "button" onclick = "toggle()" value = "click"/></td></tr> 
. 
. 
. 
</table> 

<script> 
function toggle(){ 
//I want to fetch the value of the Name attribute for the row in which my button was clicked. and later I want to call an ajax call to a url that will consist of Update query. 
} 
</script> 
+0

請給我們展示一些代碼 – jantimon 2013-05-14 09:58:44

回答

1

首先你要調用的「屬性」是一個「元素」。

其次排除了inline onclick=屬性。

然後,用一些適當的jQuery方法:

$(document).ready(function() { 
    $("table td input[type='button']").click(function() { 
     var name = $(this).closest('tr').children().eq(1).text(); 
     // do something with name 
     alert(name); 
    }); 
}); 

演示:http://jsfiddle.net/EVuGV/1

也就是說,一個單擊處理程序綁定到表中的所有輸入按鈕元素(理想地你給你的表id屬性並使用該屬性,例如$("#idOfTable td"))。在該函數中,this將被設置爲被點擊的特定按鈕,因此您可以使用jQuery的DOM導航方法進入包含tr元素,然後在tr的孩子中選擇第二個並獲取其文本。

+0

好的:)感謝很多... :) – Saurabh 2013-05-14 10:11:38

0

試試這個:

HTML

<input type="button" value="click"/> 

SCRIPT

<script> 
    $(function(){ 
     $("table td input[type='button']").on('click',function() { 
     console.log($(this).closest('tr').find('td:eq(1)').text();) 
     } 
    }); 
</script> 
0

http://jsfiddle.net/2dJAN/28/

$('input[type=button]').click(function(){ 
    alert($(this).closest('tr').find('td:nth-child(2)').html()); 
}); 

請參閱示例。

注意:我編寫了代碼來獲取該行的「Name」值。

+0

請注意,如果表包含在另一個表的父母'('tr')'將從兩個表中獲得包含tr元素.. 。更合適的選項是'.closest('tr')'。 – nnnnnn 2013-05-14 10:16:10

+0

謝謝Mr.nnnnnn。現在我改變了我的代碼,將.parents()的值傳遞給.closest() – vinothini 2013-05-14 10:21:16

相關問題