我是 jQuery
的新手并与 .toggle()
作斗争功能。
我想显示几个<div>
-相同位置的元素......但一次只有一个。如果一个<div>
打开并且“切换”另一个不同的它应该自动关闭。
HTML:
$(document).ready(function() {
$("#button1").click(function() {
$("#box1").toggle(1000);
});
});
$(document).ready(function() {
$("#button2").click(function() {
$("#box2").toggle(1000);
});
});
.container {
width: 90px;
}
.box1 {
background-color: green;
color: red;
display: none;
}
.box2 {
background-color: blue;
color: yellow;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class=box1 id=box1>
This is Box 1
</div>
<div class=box2 id=box2>
This is Box 2
</div>
</div>
<a href="#" id="button1">Box1</a>
<a href="#" id="button2">Box2</a>
此外,我很确定我只需要一个 toggle()
函数而不是 4 对于我要实现的任务……但是尝试调用同一个任务似乎不适用于我的不同 id
/class
.
我在这里做错了什么/遗漏了什么?
最佳答案
一般情况下,您可以使用单个文档就绪功能。
在这种情况下,您还可以使用单个 click
函数来处理切换。由于您使用的是触发器链接,因此您需要一种方法来引用目标框,但像这样的方法可以与附加属性一起使用以获取框名称。 (您也可以使用索引来做到这一点,但为了便于使用,我添加了一个 target-box
属性,它具有所需框的 ID。)
我还向两个 div 添加了相同的 box
类,您可以删除单独的 box1/box2
类,因为您已经有了处理差异的 ID。
我还向链接添加了一个 toggle
类,为它们提供更语义化的选择器,并删除了不必要的“打开/关闭”重复项(因为 toggle
被设计为处理两者)
jQuery(document).ready(function($){
$('.toggle').on('click', function(){
var targetBox = $(this).attr('target-box'); // Find the target box
$('.box').not(targetBox).hide(1000); // Hide all other boxes
$(targetBox).toggle(1000); // Toggle the current state of this one
});
});
.container {
width: 90px;
}
.box1 {
background-color: green;
color: red;
display: none;
}
.box2 {
background-color: blue;
color: yellow;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="box box1" id="box1">
This is Box 1
</div>
<div class="box box2" id="box2">
This is Box 2
</div>
</div>
<a href="#" class="toggle" target-box="#box1">Toggle Box1</a>
<a href="#" class="toggle" target-box="#box2">Toggle Box2</a>
关于javascript - 在同一位置仅切换一个 div 元素(隐藏所有其他 div),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50338929/