2012-10-21 30 views
1

我有以下代码,用于常见问题列表。当用户点击按钮时,信息向下滑动以显示内容。然后他们可以点击相同的按钮关闭内容。在打开和关闭列表之间切换

因为我在这个页面上有多个列表,我想要的是如果一个列表是打开的,并且用户单击另一个列表打开它,则打开列表关闭,另一列表打开。这样一个用户没有一英里长的滚动条。

这里是我的代码:

JS

$('.service').live('click',function(){ 
    $(this).parent().children().toggle(); //swaps the display:none between the two spans 
    $(this).parent().parent().find('.content').slideToggle(); //swap the display of the main content with slide action 
}); 

$('.service').click(function(e) { 
    e.preventDefault(); //Prevents link from taking them to top of page 
}); 

HTML

<div class="service-container"> 
<div class='service-title'> 
    <a href="#" class="service fancy_button"><span style="background-color: #0f071e;"><i class="icon-plus"></i> Open</span></a> 
    <a href="#" class="service fancy_button" style="display:none;"><span style="background-color: #666;"><i class="icon-minus"></i> Close</span></a> 
    </div> 
    <div class='content' style='display:none;'> 
     <p>My Content</p> 
    </div> 
</div> 

,如果有一个我不介意重新编写代码更好的方法这个。

的想法:

screenshot

回答

2

主要是我建议你不要使用live()方法,因为它已经过时了。

$(".service-title").on("click", ".service", function(e) { 
    $(this).siblings().andSelf().toggle() 
     .parent().siblings(".content").slideToggle(); 

    e.preventDefault(); 
}); 

DEMO:http://jsfiddle.net/bnT6Q/

为了使当前打开时,其他已打开容器封闭,我们可以重写代码位:

相反,您可以通过以下方式使用方法 on()
$(".service-title").on("click", ".service", function(e) { 
    $(".service-container") 
     .has($(".content:visible").add(this)) 
     .find(".service").toggle().end() 
     .find(".content").slideToggle(); 

    e.preventDefault(); 
});​ 

DEMO:http://jsfiddle.net/bnT6Q/1/

+0

感谢您的帮助和代码改进。但有一个问题,我如何关闭当前打开的框?我添加了一张显示我的想法的截图。 – L84

+0

@Lynda那不是按照你的计划工作吗?我的小提琴呢。 – VisioN

+0

当您单击第二个打开框时,第一个应该关闭而不能保持打开状态。你的小提琴没有这样做。 – L84