2013-06-18 26 views
0

我的表是這樣的特定列中的每個元素jQuery的獲得表

<table> 
    <tr> 
     <td> 
      <img src="" /> 
      <span>blah</span> 
     </td> 
    </tr> 
    ... 

所以每行第一列中包含的圖像。我需要在每張圖片上註冊活動。那我該如何選擇它?

我嘗試這樣做:

td:eq(0):nth-child(0) 

但它無法正常工作。

回答

1

我建議:

$('table tr td:first-child img').on('event', function(){ 
    // handle the event here 
}); 
+0

您應該使用子選擇器'>'使選擇器更具體(更快)。 – RoToRa

0

看到,只要你想一個事件附加,而不是遍歷每個圖像的圖像,你可以綁定事件處理程序是這樣的:

$("table").on("eventname", "td:first-child img", function(i){ 
//your code 
}); 

演示:http://jsfiddle.net/hungerpain/PYFhw/

+0

你似乎錯過了點s omewhat:他只需要將事件附加到表格第一列中的圖像,而不是表格中的所有圖像。 –

+0

@AleksG看到標題「jQuery獲取**每個** 元素在表格的特定列」,並且這句話「我需要註冊事件**每個**這個圖像」並且變得困惑:) .. – krishgopinath

+3

我認爲您的更新解決方案仍然是錯誤的:OP需要第一列中的圖像,而不是第一行。此外,選擇器是':first-child',而不是':first' –

2

這樣的選擇:

td:first-child > img 

應該工作我猜...

0
$('table > tr > td:first-child > img').bind('click', function() { 
    // your code 
}); 

我會給表的唯一ID爲更精確。

$('#table_id > tr > td:first-child > img').bind('click', function() { 
    // your code 
}); 

替換代碼「點擊」以上wathever事件中,你需要檢查。

+0

這將針對'td'內的所有圖像,OP只想要位於第一列的圖像 – billyonecan

+0

@billyonecan oops,我錯過了這個細節: ) – Stephan

2

對於nth-child選擇,該指數是基於1。我覺得這樣的事情會爲你工作:

$("td:nth-child(1) > img") 

或更簡單:

$("td:first-child > img") 
0

您可以選擇表格的第一欄相關圖片如下:

$('tr').find('td:eq(0)') 
0

檢查這

$(function(){ 
$("table tr td:first-child").on("click","img",function(){ 
    console.log("hey"); 
}); 
});