jQuery 手风琴,单击已打开的手风琴项目只需切换它
我有一个半工作 示例 你可以看看。
这似乎按照大多数人的意愿工作,尽管它分享了我在许多其他手风琴中看到的一个错误,即如果您单击已打开的标题链接,它将关闭,然后再次打开。
有什么优雅的解决方案吗?
这是 jQuery
<script language="javascript">
$(document).ready(function() {
// Simple Accordion Style Menu Function
$('h2.question').click(function() {
$('div.answer').slideUp('normal');
$(this).next().slideDown('normal');
});
// Closes All Divs on Page Load
$("div.answer").hide();
// Opens the first div
var Current = $('.question:first');
Current.next().show();
});
</script>
这是我想要使用的基本标记:
<div class="accordion">
<h2 class="question"><a href="#">Header 1</a></h2>
<div class="answer">
<p>some body content 1</p>
<p>some body content 2</p>
<p>some body content 3</p>
</div>
<h2 class="question"><a href="#">Header 2</a></h2>
<div class="answer">
<p>some body content a</p>
<p>some body content b</p>
<p>some body content c</p>
</div>
<h2 class="question"><a href="#">Header 3</a></h2>
<div class="answer">
<p>some body content x</p>
<p>some body content y</p>
<p>some body content z</p>
</div>
</div>
I have a semi-working example that you can look at.
This appears to work as most would desire, though it shares a bug I am seeing in many other accordions, which is if you click on the an already opened header link, it will be closed, and then opened again.
Any elegant solutions?
Here is the jQuery
<script language="javascript">
$(document).ready(function() {
// Simple Accordion Style Menu Function
$('h2.question').click(function() {
$('div.answer').slideUp('normal');
$(this).next().slideDown('normal');
});
// Closes All Divs on Page Load
$("div.answer").hide();
// Opens the first div
var Current = $('.question:first');
Current.next().show();
});
</script>
And here is the basic markup I am looking to use:
<div class="accordion">
<h2 class="question"><a href="#">Header 1</a></h2>
<div class="answer">
<p>some body content 1</p>
<p>some body content 2</p>
<p>some body content 3</p>
</div>
<h2 class="question"><a href="#">Header 2</a></h2>
<div class="answer">
<p>some body content a</p>
<p>some body content b</p>
<p>some body content c</p>
</div>
<h2 class="question"><a href="#">Header 3</a></h2>
<div class="answer">
<p>some body content x</p>
<p>some body content y</p>
<p>some body content z</p>
</div>
</div>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以尝试在 h2 上添加一个类以记录其活动状态,然后在每次单击 h2 时检查该类?如果它上面有活动类,那么什么都不做,因为它已经打开了。同样在页面加载时,它为第一个 h2.question 提供了一个活动类。
You could try adding a class on the h2 to note its active then check for that on each h2 click? If it has the active class on it then do nothing as it is already open. Also on page load it gives the first h2.question a class of active.