2

問題文:静的に作成され
たテーブルと、動的に作成されtheadた内部の 'tr/td' があります。tbody私が達成しなければならないのは、ユーザーがテーブルのどこかをクリックしたときに、クリックされval()た行の最初の列を取得する必要があるということです。

これをテストするonために、親要素クラス、つまり class for を使用してクリック イベントをバインドしていますtbodytd: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');
});

stack-overflow で多数のスレッドを調べた後、上記のコードを書きました。1 つの実用的な 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 に答える