我有 #div1
和 #div2
。 #div
默认可见,而 #div2
隐藏。单击链接时,我想隐藏 #div1
并显示 #div2
,当再次单击链接时,我想隐藏 #div2
和再次显示 #div1
。
使用以下 jQuery,我可以隐藏第一个 div 并显示 #div2
,但我不知道如何在再次单击同一链接时显示 #div1
。另外,如何根据可见的 div 切换链接标题(即切换到 div1 或 div2)
HTML:
<a class="switch" href="#">Switch to Div 2</a>
<div id="div1">Div1</div>
<div id="div2">Div2</div>
jQuery:
$(".switch").click(function() {
$('#div1').hide();
$('#div2').show();
});
CSS:
#div2 {
display: none;
}
最佳答案
尝试 toggle()
:
$(".switch").click(function() {
$('#div1, #div2').toggle();
// the following line switches the text
$(this).text('Switch to Div ' + ($('#div1').is(':visible') ? '2' : '1'));
});
关于javascript - 通过单击相同的链接更改 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19435528/