【问题标题】:Binding Click events for Dynamically added Table Rows in Javascript/jQuery在 Javascript/jQuery 中为动态添加的表行绑定点击事件
【发布时间】: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


【解决方案1】:

你的追加都搞砸了。这是您的代码已更正/正在运行。

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

【讨论】:

  • 太棒了。那行得通。 :-) 非常感谢。现在我知道我应该检查我的 HTML。仅仅看到它按预期呈现可能是不对的。 :-)
  • 我为什么不呢?那很完美。 :-) 如果您正在谈论投票支持答案,不知何故,我需要“15 名声望”才能让我的投票公开可见。我对SO相当陌生。 :-(
【解决方案2】:

通过正文附加点击事件并不理想,但在某些情况下我这样做并且效果很好。

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

【讨论】:

  • 感谢您的回复。但是,不幸的是,这并没有奏效。
  • 谢谢你,与最新版本的 jQuery 完美配合!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-16
  • 1970-01-01
  • 1970-01-01
  • 2012-05-23
  • 1970-01-01
相关资源
最近更新 更多