我已经尝试了很多次,但似乎我这边出了点问题,我想获取(检索)表格每一行的属性值,例如下面写的 productID 属性。
例如..
<button id="button">Show ID Product Attribute</button>
<table class="display" width="100%" id="example" >
<thead>
<tr>
<th>#</th>
<th>Product</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<?php
$answer = ProductsController::showProducts();
foreach ($answer as $key => $value) {
echo '<td>'.($key+1).'</td>
<td productID="'.$value["id"].'">'.$value["productName"].'</td>
<td>'.$value["price"].'</td>';
}
?>
<script type="text/javascript">
$(document).ready(function () {
var table = $('#example').DataTable();
$('#example tbody').on('click', 'tr', function () {
$(this).toggleClass('selected');
});
$('#button').click(function () {
console.log(table.rows('.selected').data()); //return all selected row data
});
});
</script>
问题是 这里 如果我选择超过 1 行并单击“显示 ID 产品属性”按钮,它会返回以下文本,但我只想访问隐藏在以下结果中的 productID 属性
{
"0": ["1", "Milk", "100"],
"1": ["2", "Tea", "200"]
}
我怎样才能找到它,非常感谢您的帮助。
您可以遍历选定的行并从该行的数组中输出相关条目:
$(document).ready(function() {
var table = $('#example').DataTable();
$('#example tbody').on('click', 'tr', function() {
$(this).toggleClass('selected');
});
$('#button').click(function() {
var rows = table.rows('.selected').data();
for (let i = 0; i < rows.length; i++) {
console.log(rows[i][0]);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.min.css" />
<button id="button">Show ID Product Attribute</button>
<table class="display" width="100%" id="example">
<thead>
<tr>
<th>#</th>
<th>Product</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td productID="1">Product 1</td>
<td>3.50</td>
</tr>
<tr>
<td>2</td>
<td productID="2">Product 2</td>
<td>24.60</td>
</tr>
<tr>
<td>3</td>
<td productID="3">Product 3</td>
<td>63.00</td>
</tr>
</tbody>
</table>
您可以使用
data-search
属性来指示 #
列的实际值,如下所示:
$(document).ready(function () {
var table = $('#example').DataTable();
$('#example tbody').on('click', 'tr', function () {
$(this).toggleClass('selected');
});
$('#button').click(function () {
let ids = [];
table.rows('.selected').every(function ( rowIdx, tableLoop, rowLoop ) {
let data = parseInt(this.data()[0]["@data-search"], 10);
ids.push(data);
});
console.log(ids); // logs all selected ids
});
});
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="//cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.min.css" />
<button id="button">Show ID Product Attribute</button>
<table class="display" width="100%" id="example" >
<thead>
<tr>
<th>#</th>
<th>Product</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr><td data-search="123">1</td><td>Milk</td><td>100</td>
<tr><td data-search="456">2</td><td>Tea</td><td>200</td>
</tbody>
</table>