2013-03-25 47 views
5

我有一個從數據庫填充的HTML表格。 還有一個jQuery的功能,將客戶端點擊事件添加到每個表格行。如何在javascript中訪問特定單擊的表格行

$(function() { 
    $(".TreeTable tr").each(function(index) { 
     $(this).click(function() { 
      alert($(this).text()); 
     }); 
    }); 
}); 

現在我可以通過單擊任何行來獲取完整的行值。 現在我需要訪問該函數中的單個單元格值。 任何人都可以告訴我如何獲得行單擊單個單元格值。

+0

我認爲您對單擊行中的多個單元格值感興趣,而不是點擊特定單元格的值? – Alnitak 2013-03-25 13:18:34

回答

7

在此請看:

$(document).ready(function(){ 
    $('.TreeTable tr').click(function(e){ 
     var cell = $(e.target).get(0); // This is the TD you clicked 
     var tr = $(this); // This is the TR you clicked 
     $('#out').empty(); 
     $('td', tr).each(function(i, td){ 
      $('#out').html(
       $('#out').html() 
       +'<br>' 
       +i+': '+$(td).text() 
       + (td===cell?' [clicked]':'')); 
     }); 
    }); 
}); 

這裏是工作代碼: http://jsfiddle.net/VbA9D/

如果您有表格單元格內的其他HTML元素上,你可能會點擊,下面的例子將更好的工作:

$(document).ready(function(){ 
    $('.TreeTable tr').click(function(e){ 
     var cell = $(e.target).get(0); // This is the TD you clicked 
     if(cell.nodeName != 'TD') 
      cell = $(cell).closest('td').get(0); 
     var tr = $(this); // This is the TR you clicked 
     $('#out').empty(); 
     $('td', tr).each(function(i, td){ 
      $('#out').html(
       $('#out').html() 
       +'<br>' 
       +i+': '+$(td).text() 
       + (td===cell?' [clicked]':'')); 
     }); 
    }); 
}); 

這裏是代碼,你可以測試:

http://jsfiddle.net/7PWu5/

+0

感謝一噸,尤其是小提琴 – 2014-01-17 10:23:00

1

您可以通過使用

alert($('td', this).eq(1).text()); 

通常情況下,一個更可靠的代碼獲得第二小區,你會喜歡的一類添加到您想要的細胞,這樣就可以使用

alert($('td.myclass', this).text()); 

如果您想獲得點擊的單元格,只需將事件綁定到單元格:

$(".TreeTable td").click(function() { // td not tr 
    alert($(this).text()); 
}); 

請注意,如果要循環使用jQuery集合來綁定一個事件,就像您從上一段代碼中看到的一樣。

+1

使用DOM,Luke! – Alnitak 2013-03-25 13:19:42

5

首先,不需要.each - .click方法將綁定到每個傳遞的元素,而不僅僅是第一個。

其次,有一個名爲cells上表行的元素一個特定屬性,讓直接訪問該行的單元格:

$('.TreeTable').on('click', 'tr', function() { 
    var td = this.cells[0]; // the first <td> 
    alert($(td).text()); 
}); 

注意使用事件代表團 - 事件處理程序實際上是登記在整個表格,然後依靠事件冒泡來告訴你哪個行被點擊(並從中獲取單元格文本)。

+0

我不知道細胞屬性。大的幫助。 – 2016-08-05 23:36:57

+1

+ 1使用事件委託。效率更高,而不是將聽衆附加到1000行,例如... – fraktal12 2017-11-16 11:28:41

1

我更喜歡這樣的:

$('.TreeTable').on('click', 'td', function() { // td not tr 
    alert($(this).text()); 
}); 
1

你不需要使用.each()將事件處理程序綁定到一組元素明確迭代,事件綁定功能,將隱含爲你做的。由於事件傳播,您可以將事件處理程序綁定到<tr>和使用event.target(原始元素)獲取對實際點擊(在<td>)元素的引用:這是假設你」

$(function() { 
    $('.TreeTable tr').click(function(event) { 
     console.log(this); // the <tr> 
     console.log(event.target); // the <td> 
    }); 
}); 

對點擊的具體<td>元素感興趣。

相關問題