我正在使用启用了响应选项的jquery数据表.当表处于响应模式时,我无法返回行数据:
我的桌子:
$('#productsTable').DataTable({
responsive: true
});
Run Code Online (Sandbox Code Playgroud)
该表格包含产品代码,品牌,类别,价格和"添加到购物车"按钮的列.该按钮应该检索行数据.但是,当表处于响应模式(也就是它缩小并且某些列已经折叠)并且我单击我的按钮时,它不会返回任何数据.
我的html表:
<table id="productsTable" class="table table-striped table-bordered dt-responsive nowrap" cellspacing="0" width="100%">
<thead>
<tr>
<th>Product Code</th>
<th>Brand</th>
<th>Category</th>
<th>Price ($)</th>
<th></th>
</tr>
</thead>
<tbody>
{{#each context}}
<tr>
<td class="product_code">{{product_code}}</td>
<td class="brand">{{brand}}</td>
<td class="category">{{category}}</td>
<td class="price">{{invoice_price}}</td>
<td><button type="button" class="btn btn-primary">Add to Cart</button></td>
</tr>
{{/each}}
</tbody>
</table>
Run Code Online (Sandbox Code Playgroud)
我添加到购物车事件:
$(".btn-primary").click(function(e) {
var price = $(this).parent().parent().children('td.price').text();
var context = {
product_code: $(this).parent().parent().children('td.product_code').text(),
brand: $(this).parent().parent().children('td.brand').text(),
category: $(this).parent().parent().children('td.category').text(),
price: $(this).parent().parent().children('td.price').text(),
};
console.log(context) //console.logs context
});
Run Code Online (Sandbox Code Playgroud)
折叠表的图像:
有人可以帮忙吗?
提前致谢!
Datatables.js 将表数据存储在内存中,您应该真正在内存中查找值,而不是在 DOM 中。将数据操作逻辑与表示分开将导致代码更清晰、模块化。
您需要单击行的数据。获取该数据的一种方法是向数据表 API 提供对<tr>元素的引用。
$(".btn-primary").click(function(e) {
var $tr = $(this).closest('tr');
var rowData = $('#productsTable').DataTable().row($tr).data();
console.log(rowData);
});
Run Code Online (Sandbox Code Playgroud)
好吧,我正在寻找一个解决方案,我没有找到任何解决这个问题,所以我做了这个:
$(document).on('click', '.button', function () {//Button inside a cell
var current_row = $(this).parents('tr');//Get the current row
if (current_row.hasClass('child')) {//Check if the current row is a child row
current_row = current_row.prev();//If it is, then point to the row before it (its 'parent')
}
var data = products.row(current_row).data();//At this point, current_row refers to a valid row in the table, whether is a child row (collapsed by the DataTable's responsiveness) or a 'normal' row
console.log('Row data:'+data);
});
Run Code Online (Sandbox Code Playgroud)
谢谢楼上的两个回答。我用服务器端开发了数据表。所以我把这两件事结合在一起。这是我的服务器端数据表解决方案
$('#list_quoation tbody').on( 'click', 'button', function () {
var data = table.row( $(this).parents('tr') ).data();
// This work when data table is responsive
if(data == undefined) {
var selected_row = $(this).parents('tr');
if (selected_row.hasClass('child')) {
selected_row = selected_row.prev();
}
var rowData = $('#list_quoation').DataTable().row(selected_row).data();
window.location.href = "/preapplication/" + rowData.quot_id;
} else {
window.location.href = "/preapplication/" + data.quot_id;
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5457 次 |
| 最近记录: |