在jQuery中构建切换程序
我正试图建立一个切换基于这个 问题是我仍然找不到合适的兄弟姐妹可以在单击时进行切换在jQuery中构建切换程序,jquery,html,css,siblings,Jquery,Html,Css,Siblings,我正试图建立一个切换基于这个 问题是我仍然找不到合适的兄弟姐妹可以在单击时进行切换 <aside class="aside"> <div class="element"> <header><a href="#Cat1">Categorys</a></header> <section> <ul> <li
<aside class="aside">
<div class="element">
<header><a href="#Cat1">Categorys</a></header>
<section>
<ul>
<li><a href="">Category 1</a></li>
<li><a href="">Category 2</a></li>
<li><a href="">Category 3</a></li>
<li><a href="">Category 4</a></li>
<li><a href="">Category 5</a></li>
</ul>
</section>
</div>
<div class="element">
<header><a href="#Cat1">Categorys:</a></header>
<section>
<ul>
<li><a href="">Category 1</a></li>
<li><a href="">Category 2</a></li>
<li><a href="">Category 3</a></li>
<li><a href="">Category 4</a></li>
<li><a href="">Category 5</a></li>
</ul>
</section>
</div>
<div class="element">
<header><a href="#Cat1">Categorys:</a></header>
<section>
<ul>
<li><a href="">Category 1</a></li>
<li><a href="">Category 2</a></li>
<li><a href="">Category 3</a></li>
<li><a href="">Category 4</a></li>
<li><a href="">Category 5</a></li>
</ul>
</section>
</div>
</aside>
请参阅完整代码,
谢谢。我不是100%清楚你想要实现什么,但我认为这是为了确保只有一个类别是开放的。所以我修改了你的代码:
cat.on('click', function() {
var $this = $(this),
section = $this.parent('header').next('section');
// hide open categories
$('aside section').slideUp();
// open clicked category
section.slideDown();
})
查看完整的解决方案:
更新
下面是我如何解决这个问题的,它涉及到存储哪些部分是可见的,这样就可以很容易地专门隐藏该部分,而不是隐藏除当前部分以外的所有部分:
$(function() {
// hide all sections except the first
$('.element section:not(:first)').hide();
// store what section is visible
var visible_section = $('.element section:first');
$('.element header > a').click(function() {
// hide the visible section
visible_section.slideUp();
// show the current section
var section = $(this).parent().next('section');
section.slideDown();
// update the new visible section
visible_section = section;
})
});
您的分区不是兄弟。你可以这样做
cat.on('click', function() {
var $this = $(this),
section = $this.parent('header').next('section');
section.slideDown();
$('.element section').not(section).slideUp(); // all sections but current one slide up
})
这里是另一个只显示一个部分的解决方案
$(function() {
$("header a").click(function(event) {
event.preventDefault();
$("section").hide();
$(this).parent().next("section").show();
});
$("section").not(".first").hide();
});
试试我创建的JSFIDLE: 您的脚本与我的脚本的主要区别在于:
$this.parents('.element').siblings().find('section').slideUp();
这会导致当前部分在第一次单击后再次上下滑动,这正是我想要的,非常简单,谢谢。@wirey是的,但我不确定需要什么,所以我只是将其组合起来,看看是否正确。我不应该用“解决方案”这个词。我认为我的最新版本是一个解决方案:请清楚地解释你想要达到的目标。看起来很简单???一个新主意!谢谢,伙计