在页面加载时自动显示 jquery 手风琴的 1 部分,而不是最初隐藏所有部分
我有以下 Javascript 代码,它控制手风琴类型的 div 集。 这组 div 是这样构建的:
<h1>click here to show next div</h1>
<div>text to show</div>
<h1>click here to show next div</h1>
<div>text to show</div>
<h1>click here to show next div</h1>
<div>text to show</div>
我假设你们都知道手风琴是如何工作的。 H1 标签是 onclick 的触发器,它显示下一个 div 但隐藏所有其他 div。
<script language="javascript"><!--
$(document).ready(function(){
toggler();
});
function toggler() {
$('.trigger').click( function() {
if ( $(this).hasClass('trigger_active') ) {
$(this).next('.toggle_container').slideToggle('fast');
$(this).removeClass('trigger_active');
} else {
$('.trigger_active').next('.toggle_container').slideToggle('fast');
$('.trigger_active').removeClass('trigger_active');
$(this).next('.toggle_container').slideToggle('fast');
$(this).addClass('trigger_active');
};
return false;
});
}
//--></script>
现在,在页面加载时,所有 div 都将被关闭,这有点愚蠢。 我现在想做的是在页面加载时激活第一个 div,这样用户就不必单击它。 你知道如何做到这一点吗? 我试图给第一个 div 一个唯一的 ID 并在 DOM 加载时 show() 它,但是如果我单击其他触发器它就不会崩溃(它永远不会隐藏)
I have the following Javascript code which controls an accordion type set of divs.
The set of divs is built this way:
<h1>click here to show next div</h1>
<div>text to show</div>
<h1>click here to show next div</h1>
<div>text to show</div>
<h1>click here to show next div</h1>
<div>text to show</div>
I assume you all know how an accordion works. H1 tag is the trigger onclick which shows the next div but hides all other divs.
<script language="javascript"><!--
$(document).ready(function(){
toggler();
});
function toggler() {
$('.trigger').click( function() {
if ( $(this).hasClass('trigger_active') ) {
$(this).next('.toggle_container').slideToggle('fast');
$(this).removeClass('trigger_active');
} else {
$('.trigger_active').next('.toggle_container').slideToggle('fast');
$('.trigger_active').removeClass('trigger_active');
$(this).next('.toggle_container').slideToggle('fast');
$(this).addClass('trigger_active');
};
return false;
});
}
//--></script>
Now on page load all divs will be closed, which is kind of stupid.
What I want to do now is have the first div being activated on page load, so the user doesn't have to click on it.
You have any idea how to do this?
I tried to give the first div a unique ID and show() it on load of DOM, but then it won't collapse if I click on other triggers (it will never hide)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以在加载时触发第一次实际点击:
但是,在您的 HTML 中没有
.trigger
,这是正确的吗?You can trigger an actual click for the first on load:
However, in your HTML there are no
.trigger
s, is that correct?在页面加载时模仿点击事件对我来说并不干净。您可能只需要为您的第一个项目分配类别。查看这个 jsFiddle 作为示例。
Mimicking a click event on page load doesn't feel clean to me. You might need just to assign the classes for your first items. Check this jsFiddle for an example.
您可以在页面加载方法中调用.trigger的click函数
You can call click function of the .trigger on page load method