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

时间:2018-05-25 12:36:50

标签: javascript jquery datatables jquery-events

我已阅读了多篇文章和jQuery API文档,并了解除{event}之外的click()on('click')之间没有区别。

我在我的页面中使用Datatables及其选择插件;我的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')相同时,我必须获得相同的控制台结果,但我得到的是在选择第一行(data-id=1)之后

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

然后单击第一行的第二行

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

我发现on('click()')在数据表的选择例程之前运行,而click()在运行之后运行click()。应用的可能修复方法是什么,以便on(click())on(click())在数据表选择例程之后执行。

由于我表中的数据集数量巨大,我需要应用委托,即this

更新

在事件中使用undefined将提供对所选行的访问权限,但在数据表中第二次单击同一行将删除选择,因此两个函数的结果应为login User table

1 个答案:

答案 0 :(得分:1)

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