2017-07-06 111 views
0

我有一個表格,其中的信息根據點擊按鈕而改變。目前它的工作原理是當我使用toggle()命令但有切換()會一次選擇多個按鈕導致顯示錯誤的數據。我試過.show()方法,它不起作用。有沒有一種方法可以只強制執行一個按鈕,或者刪除切換按鈕,並且每次只顯示一個按鈕。Javascript更改表格內容點擊

<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()命令在單擊時不起作用。

回答

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(); 
});