在通过提交表单加载jQuery DataTable之后,是否有任何方法可以用单击的行的值来完成数组


大家好,我在使用jQuery数据表时遇到了一个问题。加载Datatable后,通过向服务器提交ID,然后服务器用我渲染到Datatable中的数据进行响应。在那个DataTable中,我想要进行多行选择,并且我想要推送到数组中的值是例如第一列的所有值。下面的代码就是我现在创建的所有内容。HTML代码:
<form name="search_form_order" id="search_form_order" novalidate="">
<input type="text" name='login_id' id="login_id" class='form-control'>                       
<button type="submit" name="search" id="search">Search</button>
</form>  
<table id="orders_table" width='100%'>
<thead>
<tr>
<th>Login ID</th>
<th>Order ID</th>                                
<th>Comment</th>
<th class="disabled-sorting">Actions</th>
</tr>
</thead>
<tfoot>
<th>Login ID</th>
<th>Order ID</th>                                
<th>Comment</th>
<th class="disabled-sorting">Actions</th>
</tfoot>
</table>

jQuery代码:

//This is the part where user submit the id parameter  
$('#search_form_order').on('submit', function(event) {
event.preventDefault();
var id = $('#login_id').val();
$('#orders_table').DataTable().destroy();
loadOrdersTable(id);    
});
//This is the function  
function loadOrdersTable (id) {
table=$('#orders_table').DataTable({
responsive: true,
processing: true,
serverSide: false,
lengthMenu: [[100, -1], [100, "All"]],
"ajax": {
url: "/list_orders.php",
type:"POST",
dataSrc: "",
data: {login_id:id}
}, 
columns: [
{data: 'login_id', name: 'login_id'},
{data: 'order_id', name: 'order_id'},
{data: 'comment', name: 'comment'}, 
{data: 'actions', name: 'actions'}
]
});   
}

在这里之前,一切都很完美,但当我想选择每行的order_id-s时,下面的jQuery代码不起作用:

var dataArr = []; 
$('#orders_table tbody').on('click', 'tr', function () { 
$(this).toggleClass('selected');        
var id= $(this).find('td').eq(1).text();
dataArr.push(id);
}); 
console.log(dataArr); 

我之所以使用它,是因为我想填充这个数组,对所有选定的行进行批量编辑或批量删除。在控制台上,它只显示这个"[]",作为输出,因为onlcik事件不会从表行中获取值。

谢谢!

您的错误是将console.log放在事件处理程序之外。这意味着它在加载页面时执行,因此数组为空。

如果您将其移动到事件处理程序中(之前为1(,您会发现每次单击时,ID都会被推送到数组中,然后显示在控制台中。

以下是一个工作片段:

PD:注意,每次你点击一行,ID就会被添加到数组中,导致可能的重复,同时切换会。。切换,可能会导致意外行为。你应该添加额外的逻辑来避免

var dataArr = []; 
$('#orders_table tbody').on('click', 'tr', function () { 
$(this).toggleClass('selected');        
var id= $(this).find('td').eq(1).text();
dataArr.push(id);
console.log(dataArr); 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="orders_table" width='100%'>
<thead>
<tr>
<th>Login ID</th>
<th>Order ID</th>                                
<th>Comment</th>
<th class="disabled-sorting">Actions</th>
</tr>
</thead>
<tbody>
<tr>
<td>login_id</td>
<td>order_id</td>
<td>comment</td>
<td>actions</td>
</tr>
</tbody>
<tfoot>
<th>Login ID</th>
<th>Order ID</th>                                
<th>Comment</th>
<th class="disabled-sorting">Actions</th>
</tfoot>
</table>

最新更新