Javascript在点击时更改表格内容

时间:2017-07-06 18:26:18

标签: javascript jquery html

我有一个表格,根据按钮点击的内容,信息会发生变化。目前它在我使用toggle()命令时有效,但是让toggle()一次选择多个按钮会导致显示错误的数据。我尝试过.show()方法但它不起作用。有没有办法可以强制一次只切换一个按钮,或者删除切换按钮,一次只显示一个按钮。

<button type="button" class="btn btn-primary" id="one" value="Toggle table">Example 1</button>
<button type="button" class="btn btn-primary" id="two">Example 2</button>
<button type="button" class="btn btn-primary" id="three">Example 3</button>
<button type="button" class="btn btn-primary" id="four">Example 4</button>
<button type="button" class="btn btn-primary" id="five">Example 5</button>
<button type="button" class="btn btn-primary" id="six">Example 6</button>
<button type="button" class="btn btn-primary" id="seven">Example 7</button>

<!--Table code -->
<div class="tab-content">
<table class="table table-condensed" id="table">
<!--Table code -->
</table>
</div>

<!-- Javascript -->
$(document).ready(function()
{
$("#one").click(function()


{
    var $day1 = $("#table tbody tr").filter(function () {
    return $.trim($(this).find("td").eq(0).text()) !== "0"
}).show();
});

 $("#two").on("click", function()
{
    var $rowsNo = $("#table tbody tr").filter(function () {
    return $.trim($(this).find("td").eq(0).text()) !== "1"
}).show();
});


$("#three").on("click", function()
{
    var $rowsNo = $("#table tbody tr").filter(function () {
    return $.trim($(this).find("td").eq(0).text()) !== "2"
}).show();
});

$("#four").on("click", function()
{
    var $rowsNo = $("#table tbody tr").filter(function () {
    return $.trim($(this).find("td").eq(0).text()) !== "3"
}).toggle();
});

$("#five").on("click", function()
{
    var $rowsNo = $("#table tbody tr").filter(function () {
    return $.trim($(this).find("td").eq(0).text()) !== "4"
}).toggle();
});

如上所述,切换工作正常,但可以同时切换多个按钮,导致表中显示错误数据。有没有办法限制一个按钮切换?如果不是,单击时show()命令不起作用。

1 个答案:

答案 0 :(得分:3)

hide()之前添加filter(),以便show()仅显示所需内容

$("#one").click(function() {
   $("#table tbody tr").hide().filter(function() {
    return $.trim($(this).find("td").eq(0).text()) !== "0"
  }).show();
});

您也可以通过为过滤器值添加公共类和数据属性来简化所有按钮的使用。

<button  class="btn btn-primary filter-btn" data-filter="1">Example 2</button>

$(".filter-btn").click(function() {
   var filterVal = $(this).attr('data-filter');
   $("#table tbody tr").hide().filter(function() {
    return $.trim($(this).find("td").eq(0).text()) !== filterVal ;
  }).show();
});
相关问题