假设我有多个显示特定信息的表,我将如何以尽可能干净的方式显示所选的表而隐藏其他表。
我已经想出了下面的工作,但肯定不是最干净的方式,我相信。
我考虑过一些其他方法,如jQuery附加和切换,但还没有找到可行的解决方案。
<table id="table-1">
<th>Table Heading</th>
<tr>
<td>Sample Text</td>
</tr>
</table>
<table id="table-2">
<th>Table Heading</th>
<tr>
<td>Sample Text</td>
</tr>
</table>
<table id="table3">
<tr>
<th>Table Heading</td>
</tr>
<tr>
<td>Sample Text</td>
</tr>
</table>jQuery
$("#text-one").click(function () {
$("#table-1").show();
$("#table-2").hide();
$("#table-3").hide();
});
$("#text-two").click(function () {
$("#table-2").show();
$("#table-1").hide();
$("#table-3").hide();
});
$("#text-three").click(function () {
$("#table-3").show();
$("#table-1").hide();
$("#table-2").hide();
});发布于 2017-04-01 19:39:08
您可以在自定义data-*前缀属性中持久化目标,可以使用.data()访问该属性。
向BUTTON和TABLE元素中添加一个公共类,然后可以使用(".class")绑定事件处理程序。
HTML
<button type="button" class="btn" data-target="#table-1">Button 1</button>
<button type="button" class="btn" data-target="#table-2">Button 2</button>
<button type="button" class="btn" data-target="#table-3">Button 3</button>
<table class="table" id="table-1"></table>
<table class="table" id="table-2"></table>
<table class="table" id="table-3"></table>脚本
$(".btn").click(function () {
var targetSelector =$(this).data('target');
var target = $(targetSelector);
target.show();
$(".table").not(target).hide();
});
$(".btn").click(function() {
var targetSelector = $(this).data('target');
var target = $(targetSelector);
target.show();
$(".table").not(target).hide();
});.table {
display: none
}<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="btn" data-target="#table-1">Button 1</button>
<button type="button" class="btn" data-target="#table-2">Button 2</button>
<button type="button" class="btn" data-target="#table-3">Button 3</button>
<table class="table" id="table-1">
<tr>
<th>Table Heading 1</th>
</tr>
<tr>
<td>Sample Text</td>
</tr>
</table>
<table class="table" id="table-2">
<tr>
<th>Table Heading 2</th>
</tr>
<tr>
<td>Sample Text</td>
</tr>
</table>
<table class="table" id="table-3">
<tr>
<th>Table Heading 3</th>
</tr>
<tr>
<td>Sample Text</td>
</tr>
</table>
https://stackoverflow.com/questions/43161129
复制相似问题