DataTable select 插件和 jquery 事件处理程序问题

DataTable select plugin and jquery event handler issue

我已经阅读了几篇文章和 jQuery API 文档并了解 click()on('click') 除了事件委托外没有区别。

并且我在我的页面中使用了 Datatables 及其 select 插件;我的 Html 标签和脚本与以下代码相同。

<div class='panel'>
    <table class='data-table'>
        <thead>
            <tr>
                <th>Column 1</th>
                <th>Column 2</th>
            </tr>
        </thead>
        <tbody>
            <tr data-id='1'>
                <td>Row 1, 1</td>
                <td>Row 1, 2</td>
            </td>
            <tr data-id='2'>
                <td>Row 2, 1</td>
                <td>Row 2, 2</td>
            </td>
            <tr data-id='3'>
                <td>Row 3, 1</td>
                <td>Row 3, 2</td>
            </td>

        </tbody>
    </table>
</div>

<script>
    $('table tbody tr').click(function(){
        console.log("Click(): " + $('table tr.selected').data('id'));
    });
    $('table').on('click', 'tbody tr', function() {
        console.log("On(Click()): " + $('table tr.selected').data('id'));
    });
</script>

click()on('click') 相同时,我必须获得相同的控制台结果,但我得到的是在 selecting 第一行 (data-id=1)

On(Click()): undefined
Click(): 1

然后单击第一行的第二行

On(Click()): 1
Click(): 2

我看到 on('click()') 在 data-table 的 selection 例程之前运行,而 click() 在其之后运行。可能应用什么修复程序,以便 click()on(click()) 在数据 tables selection 例程之后执行。

由于我的 table 中的数据集数量庞大,我需要申请委托,即 on(click())

更新

在事件中使用 this 将可以访问 get selected 行,但在数据中第二次单击同一行-table 将删除 selection,因此两个函数的结果应该是 undefined

在您的 jquery 选择器中,改用 this 关键字:

$('table tbody tr').click(function(){
    if($(this).hasClass( "selected" ) == true) {
        console.log("Click(): " + $(this).data('id'));
    }
});
$('.data-table').on('click', 'tbody tr', function() {
    if (!$(this).hasClass('selected'))
        console.log("On(Click()): " + $(this).data('id'));
    else
        console.log('nothing selected');
});