2

问题陈述:
我有一个静态创建的表,并且在动态创建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 示例

但是,它不适用于我上面编写的代码。能否以某种方式向我指出为什么不起作用以及如何解决?

4

2 回答 2

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');
});

演示

于 2015-09-02T21:29:11.487 回答
1

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

$("body").on("click", "#table-body-id tr", function(){
    alert($(this));
});
于 2015-09-02T20:54:57.490 回答