在Javascript / jQuery中为动态添加的表行绑定Click事件
问题陈述:我有一个静态创建’thead’的表,动态创建的’tbody’中有’tr / td’。 我必须实现的是,当用户单击表中的任何位置时,我需要获取被单击的行的第一列的val()。
为了测试这个,我使用’on’绑定一个click事件到父元素类,即’tbody’的类。 并且,我正在尝试更新单击行的第一列“td:first”中的文本,例如“clicked”。
然而,不知何故事件没有被捕获。 这是JSfiddle的摘录 。
HTML:
Edit Name Status
表创建
var container = $('.table-body'); ['A', 'B'].forEach(function(index){ $('', {class: 'table-row', id: 'table-row-id-'+index}).appendTo(container); $(' ', {class: 'edit', id: 'edit-id-'+index, value: index}).appendTo(container); $(' ', {class: 'name', id: 'name-id-'+index, text: 'Mr. '+index}).appendTo(container); $(' ', {class: 'status', id: 'status-'+index, text: 'MSc'}).appendTo(container); $(' ').appendTo(container); });
绑定点击事件
$("#table-body-id").on("click", "tr", function(){ alert($(this).find('td:first').val()); $(this).find('td:first').text('clicked'); });
我已经查看了堆栈溢出上的大量线程,之后我编写了上面的代码。 一个工作JS-Fiddle的例子 。
但是,它不适用于我上面编写的代码。 能以某种方式请指出我为什么不工作以及如何解决它?
你的追加都搞砸了。 这是您的代码更正/工作。
var container = $('.table-body'); //Create an empty container var $trs = $(); ['A', 'B'].forEach(function(index) { //Create TR and append TDs to it var $tr = $(' ', {class: 'table-row', id: 'table-row-id-'+index}); $tr.append( $(' ', {class: 'edit', id: 'edit-id-'+index, value: index}). add($(' ', {class: 'name', id: 'name-id-'+index, text: 'Mr. '+index})). add($(' ', {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'); });
一个演示
通过身体附加点击事件并不理想,但在某些情况下,我这样做并且效果很好。
$("body").on("click", "#table-body-id tr", function(){ alert($(this)); });