问题陈述:
我有一个静态创建的表,并且在动态创建thead
的内部有“tr/td” 。tbody
我必须实现的是,当用户单击表格上的任何位置时,我需要获取val()
被单击的行的第一列。
为了测试这一点,我将一个单击事件绑定on
到父元素类,即tbody
. 而且,我正在尝试更新td:first
单击行的第一列中的文本,例如clicked
.
然而,不知何故,这些事件并没有被抓住。这是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);
});
绑定点击事件
$("#table-body-id").on("click", "tr", function(){
alert($(this).find('td:first').val());
$(this).find('td:first').text('clicked');
});
我查看了堆栈溢出上的过多线程,然后我编写了上面的代码。一个有效的 JS-Fiddle 示例。
但是,它不适用于我上面编写的代码。能否以某种方式向我指出为什么不起作用以及如何解决?