【发布时间】:2015-09-02 20:44:07
【问题描述】:
问题陈述:
我有一个静态创建的thead 表,以及动态创建的tbody 内的“tr/td”。我要实现的是,当用户点击表格上的任意位置时,我需要获取被点击的行的第一列的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');
});
我查看了堆栈溢出上的过多线程,然后我编写了上面的代码。一位working JS-Fiddle example。
但是,它不适用于我上面编写的代码。能否以某种方式指出我为什么不工作以及如何解决它?
【问题讨论】:
-
不确定是否是 C+P 错误,但您的 javascript 访问
#table-body-id并且您的表的 id 为table-id。
标签: javascript jquery jquery-events dynamic-tables event-binding