如何根据按钮单击填充表

时间:2017-02-01 10:54:15

标签: javascript jquery

我有一张表格,其中包含一些有关汽车制造的数据。

看起来像这样:    enter image description here

现在在表格中显示所有品牌的数据,但我需要仅为我点击过的品牌显示数据。例如,如果我点击奥迪仅显示此品牌的数据。

这是我填写表格的视图:

<div class="row">
    @{var testList = Model.ProductMatchingVehicles.GroupBy(p => p.Make.Name).ToList(); foreach (var item in testList) {
    <div class="btn btn-danger btnMake" data-id="@item.Key" id=btnMake onclick="myFunction()">@item.Key</div>
    } }
</div>
<div class="row">
    <div class="col-xs-12">
        <table class="table table-condensed table-striped table-bordered">
            <thead>
                <tr>
                    <th>Make</th>
                    <th>Model</th>
                    <th>Engine</th>
                    <th>Data</th>
                    <th></th>
                </tr>
            </thead>
            <tbody>
                @if (Model.ProductMatchingVehicles != null) { foreach (var item in Model.ProductMatchingVehicles) {
                <tr>
                    <td>@item.Make.Name</td>
                    <td>@item.Model.Name</td>
                    <td>@item.Engine.Name</td>
                </tr>
                } }
            </tbody>
        </table>
    </div>
</div>

你能告诉我如何在javascript或jquery中实现这个目的吗?谢谢!

1 个答案:

答案 0 :(得分:2)

您可以尝试使用以下代码:

1)修改<tbody>,如下所示:

<tbody>
    @if (Model.ProductMatchingVehicles != null) { foreach (var item in Model.ProductMatchingVehicles) {
    <tr class="vehicle_rows" data-refId="@item.Key">
        <td>@item.Make.Name</td>
        <td>@item.Model.Name</td>
        <td>@item.Engine.Name</td>
    </tr>
    } }
</tbody>

我们在此处为每个class

添加了data-refId<tr>属性

2)稍微修改按钮点击功能:

<div class="btn btn-danger btnMake" data-id="@item.Key" id=btnMake onclick="myFunction(this)">@item.Key</div>

这里将this引用传递给函数

3)函数myFunction将具有如下逻辑:

function myFunction(obj){
    var $button = $(obj);
    var car_make = $button.data("id"); //reading the data-id of clicked button

    //hide all rows first
    $(".vehicle_rows").hide();

    //show only currenly clicked buttons associated rows
    $(".vehicle_rows[data-refId="+car_make+"]").show();
}