jQuery 切换显示/隐藏 Div
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18747427/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Toggle Show / Hide Divs
提问by JeffVader
I'm using the following jQuery and HTML to show and hide divs when the links are clicked.
单击链接时,我使用以下 jQuery 和 HTML 来显示和隐藏 div。
This works well if I click Brazil the div is shown correctly. However if I then click America that is also shown but Brazil isn't hidden.
如果我单击巴西,这很有效,div 显示正确。但是,如果我然后单击也显示的美国,但未隐藏巴西。
How do I toggle the display so only one div is show at any one time.. ?
如何切换显示以便在任何时候只显示一个 div..?
$(document).ready(function() {
$('.toggle').prev().data('is_visible', true);
$('.toggle').hide();
$('a.togglelink').click(function() {
$(this).data('is_visible', !$(this).data('is_visible'));
$(this).parent().next('.toggle').toggle('slow');
return false;
});
});
<ul id="list">
<li><a href="#" class="togglelink">America</a></li>
<div class="toggle" style="display: block;"><p>America - USA - the States</p></div>
<li><a href="#" class="togglelink">Brazil</a></li>
<div class="toggle" style="display: block;"><p>Brazil - Federative Republic of Brazil</p></div>
</ul>
</div>
回答by adeneo
Start by fixing the markup, a DIV can not be a direct child of an UL.
从修复标记开始,DIV 不能是 UL 的直接子代。
<ul id="list">
<li>
<a href="#" class="togglelink">America</a>
<div class="toggle" style="display: block;">
<p>America - USA - the States</p>
</div>
</li>
<li>
<a href="#" class="togglelink">Brazil</a>
<div class="toggle" style="display: block;">
<p>Brazil - Federative Republic of Brazil</p>
</div>
</li>
</ul>
Then do:
然后做:
$(document).ready(function () {
$('.toggle').hide();
$('a.togglelink').on('click', function (e) {
e.preventDefault();
var elem = $(this).next('.toggle')
$('.toggle').not(elem).hide('slow');
elem.toggle('slow');
});
});
回答by franchez
I think you're doing things too complicated with your data binding. Can you please check my example DEMO
我认为你的数据绑定做得太复杂了。你能看看我的示例演示吗
This do the job:
这做的工作:
$(document).ready(function() {
$('.toggle').hide();
$('a.togglelink').click(function() {
$('.toggle').hide();
$(this).parent().next('.toggle').toggle('slow');
return false;
});
});
});