根据类选择数据表数据

时间:2016-01-26 01:35:02

标签: javascript jquery datatables

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

我的表:

<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>

如果我点击我的Add to Cart按钮,我希望它根据类别选择product_id and 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

但是这种方法对我来说不起作用,因为列可能在不同的位置从一个表到另一个表。

提前致谢!

1 个答案:

答案 0 :(得分:1)

你可以这样做。

    namespace app\models;

    use yii\base\Model;
    use yii\web\UploadedFile;

    /**
    * UploadForm is the model behind the upload form.
    */
    class UploadForm extends Model
    {
    /**
     * @var UploadedFile|Null file attribute
     */
   public $uploadedFiles;

    /**
     * @return array the validation rules.
     */
    public function rules()
    {
        return [
            [['uploadedFiles'], 'file'],
        ];
    }
    }
    ?>

这是fiddle