1

問題陳述: 我有一個靜態創建的'thead'表,以及動態創建的'tbody'內的'tr/td'表。我必須實現的是,當用戶點擊桌子上的任何位置時,我需要獲取被點擊的行的第一列的val()。在Javascript/jQuery中動態添加表格行的綁定點擊事件

爲了測試這個,我使用'on'綁定了一個單擊事件給父元素類,即'tbody'的類。而且,我正在嘗試更新點擊行的第一列「td:first」中的文本,例如「點擊」。

但是,不知何故事件並未被捕獲。這裏是來自JSfiddle的摘錄。

HTML:

<table class="table" id="table-id"> 
    <thead> 
     <tr class="table-header"> 
      <th class="edit">Edit</th> 
      <th class="name">Name</th> 
      <th class="status">Status</th> 
     </tr> 
    </thead> 
    <tbody class="table-body" id="table-body-id"> 
    </tbody> 
</table> 

表創建

var container = $('.table-body'); 
['A', 'B'].forEach(function(index){ 
    $('<tr>', {class: 'table-row', id: 'table-row-id-'+index}).appendTo(container); 
    $('<td />', {class: 'edit', id: 'edit-id-'+index, value: index}).appendTo(container); 
    $('<td />', {class: 'name', id: 'name-id-'+index, text: 'Mr. '+index}).appendTo(container); 
    $('<td />', {class: 'status', id: 'status-'+index, text: 'MSc'}).appendTo(container); 
    $('</tr>').appendTo(container); 
}); 

約束力的Click事件

$("#table-body-id").on("click", "tr", function(){ 
    alert($(this).find('td:first').val()); 
    $(this).find('td:first').text('clicked'); 
}); 

我已經看了看堆棧溢出的線程過多之後,我寫上面碼。一個working JS-Fiddle example

但是,它不適用於我上面編寫的代碼。請不知何故,請指出我爲什麼不工作,以及如何解決它?

+0

不知道,如果它是一個C + P錯誤,但你的JavaScript訪問'#表體id'和你的表有'表id'的ID。 – Luke

回答

0

通過身體附加點擊事件並不理想,但在某些情況下,我這樣做並且效果很好。

$("body").on("click", "#table-body-id tr", function(){ 
    alert($(this)); 
}); 
+1

感謝您的回覆。但不幸的是,這並沒有奏效。 – wierdmaster

+0

謝謝你,與最新版本的jQuery完美配合! –

4

你的追加都搞砸了。這是你的代碼糾正/工作。

var container = $('.table-body'); 
//Create an empty container 
var $trs = $(); 
['A', 'B'].forEach(function(index) { 
    //Create TR and append TDs to it 
    var $tr = $('<tr/>', {class: 'table-row', id: 'table-row-id-'+index}); 
    $tr.append(
     $('<td />', {class: 'edit', id: 'edit-id-'+index, value: index}). 
     add($('<td />', {class: 'name', id: 'name-id-'+index, text: 'Mr. '+index})). 
     add($('<td />', {class: 'status', id: 'status-'+index, text: 'MSc'})) 
    ); 
    //Add each tr to the container 
    $trs = $trs.add($tr); 
}); 

//Append all TRs to the container. 
container.append($trs); 

$(".table-body").on('click', 'tr', function() { 
    alert('Clicked row '+ ($(this).index()+1)); 
    //Use .text() as td doesn't have method .val() 
    //Empty first time as the td:first has no text until clicked. 
    alert($(this).find('td:first').text()); 
    $(this).find('td:first').text('clicked'); 
}); 

A demo

+0

太棒了。這工作。 :-) 非常感謝。現在我知道我應該檢查我的HTML。只是看到它按預期呈現可能是不正確的。 :-) – wierdmaster

+0

爲什麼我不?那很完美。 :-) 如果你正在談論投票的答案,不知何故,我需要'15聲望'爲我的投票公開可見。我對於SO相當陌生。 :-( – wierdmaster