简体   繁体   English

jQuery dataTables并选择一行

[英]jQuery dataTables and selecting a row

I am trying to get a jQuery dataTable to behave in such a way that a user can select a row and then click a button (located elsewhere on the page, but not on the table or in it) and have a JS alert pop up. 我试图让jQuery dataTable以这样一种方式运行,即用户可以选择一行,然后单击一个按钮(位于页面的其他位置,但不在桌面上或其中)并弹出一个JS警报。

Here is my dataTable: 这是我的dataTable:

$("#my-datatable").dataTable( {
    "bProcessing" : true,
    // Commenting out next line
    //"sDom" : 't',
    "sAjaxSource" : "some/url/on/my/server",
    "sAjaxDataProp" : "",
    "bDestroy" : true,
    "fnServerData" : function(sSource, aoData, fnCallback) {
        aoData.push({
            "name" : "asking",
            "value" : "yes"
        });

        request = $.ajax({
            "dataType" : "json",
            "type" : "GET",
            "url" : sSource,
            "data" : aoData,
            "success" : fnCallback
        });
    },

    "aoColumns" : [
        {
            "mDataProp" : "name"
        },
        {
            "mDataProp" : "expr"
        },
        {
            "mDataProp" : "seq"
        }
    ]
});

Here is my button: 这是我的按钮:

<div id="bam-btn-div">
    <input type="button" id="bam-btn" value="BAM!" onclick="bam();"/>
</div>

When the user selects a row in the dataTable, and then clicks the button, I want the following function called: 当用户在dataTable中选择一行,然后单击该按钮时,我想要以下函数调用:

function bam() {
    alert("Deleting the selected row");

    // Delete the selected row in the dataTable
}

Finally, the HTML table that the jQuery dataTable is attempting to populate: 最后,jQuery dataTable尝试填充的HTML表:

<div id="datatable-div">
    <table id="optconfig-datatable">
        <thead>
            <tr>
                <th>Name</th>
                <th>Expression</th>
                <th>Sequence</th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>
</div>

I tried to follow the example here but couldn't get anything to work. 我试着按照这里的例子但无法得到任何工作。 Can anybody spot what configurations I need to add (to the dataTable and/or otherwise)? 任何人都可以找到我需要添加的配置(到dataTable和/或其他)? Thanks in advance! 提前致谢!

You are using jQuery, you might as well stay on track. 你正在使用jQuery,你也可以保持正轨。

$('#bam-btn').on('click', function(){
    alert("BAM!");
});

On a side note, ID's must be unique, but I'm sure you know that, so make sure you're not trying to re-use the same ID over and over. 另外,ID必须是唯一的,但我相信你知道,所以请确保你不要一遍又一遍地重复使用相同的ID。

Moreover, if this element is added into the DOM after .ready() execution, you'll need to attach the event handler to a static parent element so it may delegate the click event properly. 此外,如果在执行.ready()之后将此元素添加到DOM中,则需要将事件处理程序附加到静态父元素,以便它可以正确地委派click事件。

$(document).on('click', '#bam-btn', function(){
    alert("BAM");
});

I'll leave the above in place, I don't like to delete entire portions of my answer as you never know who may find it helpful in the future 我将保留以上内容,我不想删除我的答案的所有部分,因为你永远不知道谁将来会发现它有用

First, we need to create a variable that's available to all scopes of all functions. 首先,我们需要创建一个可用于所有函数范围的变量。 This way, we can reference the variable to get a hold of the element we want to remove. 这样,我们可以引用变量来获取我们想要删除的元素。

We should place this variable outside of the document ready function 我们应该将此变量放在文档就绪函数之外

var theRow = '';
$(document).ready(function(){ 
    //existing code here
});

Now that we have a 'global scope' variable prepared, we can modify it and access it anytime. 现在我们准备了一个“全局范围”变量,我们可以随时修改它并访问它。

var theRow = '';
$(document).ready(function(){ 
    $('tr').click(function(){
        //we need to store a unique piece of information about this row.
        //Without much to go on, I'm going to rely on the index.
        theRow = $(this).index();
    });

    $('#bam-btn').click(function(){
       $('tr').eq(theRow).remove(); 
    });
});​

And here is your decent working jsFiddle as an example 这是你体面的工作jsFiddle作为一个例子

For future users, and anyone else whom may find this useful 对于未来的用户,以及可能会发现这些有用的任何其他人

The :eq() selector provided by jQuery cannot leverage .querySelectorAll() to gain a decently large performance boost. jQuery提供的:eq()选择器无法利用.querySelectorAll()来获得相当大的性能提升。 Because of this, and for the time being, you should always use .eq() over :eq() . 因此,目前,你应该总是使用.eq() :eq()

Please check that your: 请检查你的:

function bam() {
    alert("BAM!");
}

Is not in this statement: 不在此声明中:

$(document).ready(function() {
    // STATEMENT
});

If your function is in the $(document).ready() , that means it's available only in that scope, in that particular function() . 如果你的函数在$(document).ready() ,那意味着它只在那个范围内,在那个特定的function()可用。

Move your code above or below the $(document).ready() statement, and your onclick event handler in your button will be able to find it and invoke it. 将代码移到$(document).ready()语句的上方或下方,按钮中的onclick事件处理程序将能够找到并调用它。

To delete a specific element from your data-table, try with this JavaScript: 要从数据表中删除特定元素,请尝试使用以下JavaScript:

$(document).ready(function() {
    var oTable = $("#my-datatable").dataTable( {
        "bProcessing" : true,
        // Commenting out next line
        //"sDom" : 't',
        "sAjaxSource" : "some/url/on/my/server",
        "sAjaxDataProp" : "",
        "bDestroy" : true,
        "fnServerData" : function(sSource, aoData, fnCallback) {
            aoData.push({
                "name" : "asking",
                "value" : "yes"
            });

            request = $.ajax({
                "dataType" : "json",
                "type" : "GET",
                "url" : sSource,
                "data" : aoData,
                "success" : fnCallback
            });
        },

        "aoColumns" : [
            {
                "mDataProp" : "name"
            },
            {
                "mDataProp" : "expr"
            },
            {
                "mDataProp" : "seq"
            }
        ]
    });$("#my-datatable").dataTable( {
        "bProcessing" : true,
        // Commenting out next line
        //"sDom" : 't',
        "sAjaxSource" : "some/url/on/my/server",
        "sAjaxDataProp" : "",
        "bDestroy" : true,
        "fnServerData" : function(sSource, aoData, fnCallback) {
            aoData.push({
                "name" : "asking",
                "value" : "yes"
            });

            request = $.ajax({
                "dataType" : "json",
                "type" : "GET",
                "url" : sSource,
                "data" : aoData,
                "success" : fnCallback
            });
        },

        "aoColumns" : [
            {
                "mDataProp" : "name"
            },
            {
                "mDataProp" : "expr"
            },
            {
                "mDataProp" : "seq"
            }
        ]
    });

    $('button#bam-btn').on('click', function() {
        var anSelected = fnGetSelected( oTable );
        oTable.fnDeleteRow( anSelected[0] );
    } );
});

I had a similar problem with a table with dynamic data load. 我对动态数据加载表有类似的问题。 Every time I was adding contents, the old nodes disappear, losing the events linked. 每次我添加内容时,旧节点都会消失,丢失链接的事件。 I solved the problem invoking a function after the data load: 我解决了数据加载后调用函数的问题:

    function insertevents(table_id){
        var oTable = jQuery('#'+tableid).dataTable( {"bRetrieve": true });
        oTable.$('tr').click(function(){
            jQuery(this).toggleClass('row_selected');
        } );
        // Extra code here
    }

It's important to add the "bRetrieve" parameter because the table was previously initialized. 添加“bRetrieve”参数非常重要,因为该表先前已初始化。

Also, I've improved the functionality controlling keyboard events for accessibility: 此外,我已经改进了控制键盘事件的功能以实现可访问性:

        oTable.$('tr').keyup( function(event) {
            if (event.which == 13 || event.which == 32) {
                event.preventDefault();
                jQuery(this).toggleClass('row_selected');
            }       
        } ); 
        oTable.$('tr').keydown( function(event) {
            if (event.which == 13 || event.which == 32) {
                event.preventDefault(); // Desactivamos este efecto
            }
        });

This bunch of lines should replace the comment line of the first example. 这一行应该替换第一个示例的注释行。 Now the table can be used from the keyboard, selecting with intro or space key. 现在可以从键盘使用该表,使用intro或空格键进行选择。 Remember to add a tabindex=0 to the elements inserted in the table, so we can navigate with the tab key. 请记住将tabindex = 0添加到表中插入的元素,以便我们可以使用Tab键进行导航。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM