假设我有 50 个 div
,像这样:
<div class="btn1"></div> //Toggles the first container to appear
<div class="btn2"></div> //Toggles the second container to appear
<div class="btn3"></div> //Toggles the third container to appear
另外 50 个包含信息的 div
,如下所示:
<div class="container-1"><h1>This is the first container</h1></div>
<div class="container-2"><h1>This is the second container</h1></div>
<div class="container-3"><h1>This is the third container</h1></div>
是否可以在单击每个按钮时仅使用一个功能使相应的 div
切换?我已经阅读了一些关于授权和对 parent / sibling 进行操作的内容,但它似乎只适用于打开同一个容器的多个按钮,而不是每个按钮打开每个容器。
不知何故,我不认为为每个 div 编写一个函数是可行的方法。
最佳答案
是的,这是可能的。基本上,您需要添加对单击对象的引用,以便单击事件知道要显示/隐藏什么
$(function() {
$('.btn').on('click', function(e) {
var $dataTarget = $($(this).data('target'));
$dataTarget.show().siblings('.container').hide();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="btn btn1" data-target=".container-1"></div> //Toggles the first container to appear
<div class="btn btn2" data-target=".container-2"></div> //Toggles the second container to appear
<div class="btn btn3" data-target=".container-3"></div> //Toggles the third container to appear
<div class="container container-1">
<h1>This is the first container</h1>
</div>
<div class="container container-2">
<h1>This is the second container</h1>
</div>
<div class="container container-3">
<h1>This is the third container</h1>
</div>
这将显示目标容器,然后隐藏其他容器。
关于javascript - 是否可以通过使用相同的功能单击不同的元素来切换不同的 div?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45376607/