javascript - 根据类别选择数据表数据

标签 javascript jquery datatables

我试图通过单击按钮来根据行的类选择数据表数据。例如:

我的 table :

<table id="productsTable" class="display" cellspacing="0" width="100%">
    <thead>
        <tr>
            <th>Product ID</th>
            <th>Brand</th>
            <th>Category</th>
            <th>Description</th>
            <th>Price</th>
            <th></th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        {{#each context}}
        <tr>
            <td class="product_id">{{product_id}}</td>
            <td class="brand">{{brand}}</td>
            <td class="category">{{category}}</td>
            <td class="description">{{description}}</td>
            <td class="price">{{price}}</td>
            <th></th>
            <th><button type="button" class="btn btn-info" id="btn-add">Add to Cart</button></th>
        </tr>
        {{/each}}
    </tbody>
</table>

如果我点击添加到购物车按钮,我希望它根据其类别选择product_id和price。理想情况下,它会是这样的:

$("button").click(function() {
     id = this.product_id;
     price = this.price;
});

有人可以帮忙吗?

到目前为止,我最接近的是:

var table = $("#productsTable").DataTable();
var data = table.row( $(this).parents('tr') ).data();
console.log(data[4]); //selects price

但是这种方法对我来说不起作用,因为表之间的列可能位于不同的位置。

提前致谢!

最佳答案

你可以这样做。

 $("button").click(function() {
            id =  $(this).parent().parent().children('td.product_id').text();
            price = $(this).parent().parent().children('td.price').text();
        });

这是fiddle

关于javascript - 根据类别选择数据表数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35005660/

相关文章:

javascript - "neSTLing"CSS使各种高度和宽度的div占用尽可能少的空间

javascript - 在我点击鼠标的地方创建按钮

javascript - Aurelia 自定义元素数据绑定(bind)

javascript - jquery ui 拖动缓动/惯性

twitter-bootstrap - 在非事件选项卡上用 Bootstrap 装饰的 DataTable 具有窄标题

jquery - 改变 jquery 数据表 aoColumns

javascript - 甲板揭示动画

javascript - grumble.js,jQuery 插件(气泡弹出窗口): how to make it not polute my document body with unremovable trash?

javascript - 如何动态调整 Shindig Gadget 的 iframe 高度

jquery - DataTables TableTools 按钮无法正常工作(简单示例)