gpt4 book ai didi

javascript - 如何使用 JQUERY 在 HTML 中只显示被点击的元素

转载 作者:行者123 更新时间:2023-11-28 04:09:15 25 4
gpt4 key购买 nike

我有一个下面的 html 标签,它从数据库中获取数据并在 html 中显示为表格

 <html>
<body>
<div>
<button type="button" class="button">DATA_1</button>
<table class="data_table">
<tr>
<th>XXX</th>
</tr>
<tr>
<td>YYY</td>
</tr>
</table>
<button type="button" class="button">DATA_2</button>
<table class="data_table">
<tr>
<th>XXX</th>
</tr>
<tr>
<td>YYY</td>
</tr>
</table>
<button type="button" class="button">DATA_3</button>
<table class="data_table">
<tr>
<th>XXX</th>
</tr>
<tr>
<td>YYY</td>
</tr>
</table>
</div>
</body>
</html>

我有下面的脚本,默认情况下会隐藏所有表格

  $(document).ready(function(){
$('.data_table').hide();
});

按钮和表格也是自动生成的,并且是完全动态的页面。我没有任何控制来限制数据。该表将根据从数据库提供的输入数据增加。现在我想根据用户点击只显示特定记录。如果用户单击 DATA_1 按钮,它应该显示相应的表,其他应该隐藏。

我尝试使用以下脚本来显示未按预期工作的相应数据:

   $(document).ready(function(){
$('.button').on('click', function(){
$('.data_table').show();
});
});

以上代码展开所有表而不是显示/隐藏其直接子表或第一个匹配的子表。

另外,我想用下面的 html 标签做同样的事情(单击 DATA_1 按钮将显示直接类(data_table),其他将被隐藏):

  <html>
<body>
<div id="tab">
<div>
<button type="button" class="button">DATA_1</button>
</div>
<div class="logtitude">
<table class="data_table">
<tr>
<th>XXX</th>
</tr>
<tr>
<td>YYY</td>
</tr>
</table>
</div>
<div>
<button type="button" class="button">DATA_2</button>
</div>
<div class="logtitude">
<table class="data_table">
<tr>
<th>AAA</th>
</tr>
<tr>
<td>YYY</td>
</tr>
</table>
</div>
<div>
<button type="button" class="button">DATA_3</button>
</div>
<div class="logtitude">
<table class="data_table">
<tr>
<th>BBB</th>
</tr>
<tr>
<td>YYY</td>
</tr>
</table>
</div>
</div>
</body>
</html>

有人可以帮我实现这个目标吗?我想在尝试单击按钮时仅显示/隐藏直接子表或第一个匹配的子表。

最佳答案

你需要使用$(this).next()。如果您使用 $('.data_table'),它将show() 所有具有该类的表。因此,您需要使用 $(this).next()

$(document).ready(function() {
$('.data_table').hide();
$('.button').on('click', function() {
if ($(this).parent().next().find('table.data_table').is(":visible")) {
$(this).parent().next().find('table.data_table').hide();
} else {
$('.data_table').hide();
$(this).parent().next().find('table.data_table').show();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="tab">
<div>
<button type="button" class="button">DATA_1</button>
</div>
<div class="logtitude">
<table class="data_table">
<tr>
<th>XXX</th>
</tr>
<tr>
<td>YYY</td>
</tr>
</table>
</div>
<div>
<button type="button" class="button">DATA_1</button>
</div>
<div class="logtitude">
<table class="data_table">
<tr>
<th>AAA</th>
</tr>
<tr>
<td>YYY</td>
</tr>
</table>
</div>
<div>
<button type="button" class="button">DATA_1</button>
</div>
<div class="logtitude">
<table class="data_table">
<tr>
<th>BBB</th>
</tr>
<tr>
<td>YYY</td>
</tr>
</table>
</div>
</div>

关于javascript - 如何使用 JQUERY 在 HTML 中只显示被点击的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47407146/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com