jQuery、DataTables、KeyTables:如何用空格键勾选复选框
Alright, let's get this working step by step. Here's how you can integrate KeyTables into your existing DataTable setup to toggle checkboxes with the spacebar:
1. Make sure KeyTables is loaded
First, confirm you've added the KeyTables extension (it's an official DataTables plugin) to your page—you'll need its JS and CSS files loaded alongside the core DataTables resources.
2. Update your DataTable initialization
Add the keys option to your existing DataTable config to enable KeyTables functionality. You can keep it simple with keys: true, or refine it to only allow focus on specific columns if needed:
var table = $('#dataTable').DataTable({ "lengthMenu": [ [15, 30, 45, 60, -1], [15, 30, 45, 60, "All"] ], "orderMulti": true, "stateSave": true, "pagingType": "full_numbers", "autoWidth": false, "pageLength": 15, "dom": '<C<f><i><l><B<"clear">><p>rt>', // Fixed the escaped < characters "keys": true, // Enable KeyTables for row/cell navigation buttons: [ { extend: 'copyHtml5', text: '<i class="fa fa-copy"></i>', titleAttr: 'Copy' }, { extend: 'excelHtml5', text: '<i class="fa fa-file-excel"></i>', titleAttr: 'Excel' } // Fill in your remaining button config here ] });
3. Add the spacebar toggle logic
Listen for the key.dt event fired by DataTables/KeyTables, catch the spacebar press, and toggle the checkbox in the currently focused row:
table.on('key.dt', function(e, datatable, key, cell, originalEvent) { // Spacebar key code is 32 if (key === 32) { // Prevent default page scrolling when spacebar is pressed originalEvent.preventDefault(); // Find the checkbox in the currently focused row var $checkbox = $(cell.node()).closest('tr').find('input[type="checkbox"]'); // Toggle the checkbox state if it exists if ($checkbox.length) { $checkbox.prop('checked', !$checkbox.prop('checked')); // Optional: Trigger the checkbox's change event if you have dependent logic $checkbox.trigger('change'); } } });
Extra refinements (optional)
- If you only want the spacebar to work when focused on the checkbox column, add a column check:
// Replace 0 with the index of your checkbox column if (key === 32 && cell.index().column === 0) { // Toggle logic here } - Use a more specific selector for your checkboxes (e.g.,
find('.row-select-checkbox')) if you have multiple input types in your table.
内容的提问来源于stack exchange,提问作者Mormoran

