jquery 显示 :block not working correclty when more than 2 divs

标签 jquery html css

我有 3 个简单的按钮,3 个简单的 div。我需要这些 div 根据按钮点击在彼此之间切换。 这很好用。

问题:在第一页加载后,最后一个 div(示例文本 3)可见,而不是第一个(示例文本 1)。 只有第一个 div 设置为显示: block 。其余设置为显示:无。

javascript:

<script type="text/javascript">
$(window).load(function() {
    $(document).ready(function() {
    $('.content-switch').hide().eq($('.buttons a.active').index()).fadeIn("slow");
    });
    $('.buttons a').click(function() {
        $(".content-switch").eq($(this).index()).fadeIn("slow")
        .siblings('.content-switch').fadeOut("fast");
    });
});
</script>

html:

<body>
 <div class="buttons">
  <a href="#" id="button1">Button 1</a>
  <a href="#" id="button2">Button 2</a>
  <a href="#" id="button2">Button 3</a>
 </div>

 <div class="buts" id="buts">
  <div style="display: block;position:absolute" class="content-switch" id="but1">
   <p>sample text 1</p>
  </div>
  <div style="display: none;position:absolute" class="content-switch" id="but2">
   <p>sample text 2</p>
  </div>
  <div style="display: none;position:absolute" class="content-switch" id="but2">
   <p>sample text 3</p>
  </div>
 </div>
</body>

最佳答案

改变:

.eq($('.buttons a.active').index())

到:

.eq(0)

所以你有:

$('.content-switch').hide().eq(0).fadeIn("slow");
$('.buttons a').click(function () {
    $(".content-switch").eq($(this).index()).fadeIn("slow")
        .siblings('.content-switch').fadeOut("fast");
});

jsFiddle example

$('.buttons a.active').index() 返回 -1 因为没有 .buttons a.active元素,这就是第三个 div 显示的原因。

另一种解决方案是在第一个 anchor 上放置一个事件类并使用您的原始代码:

<a href="#" id="button1" class="active">Button 1</a>

jsFiddle example

关于jquery 显示 :block not working correclty when more than 2 divs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19684149/

相关文章:

jquery - 使用 jQuery 使用数组的第 n 个值填充第 n 个表单元素

jquery - CSS 和 jQuery : elements changing sizes on click/drag

javascript - 如何删除复选框生成的span标签

html - 修复表格 td 宽度

html - 减少 html tr 标签之间的默认间距

jquery - 修复了具有排序功能的标题 GridView

javascript - 使用 bootstrap 向下和向后滚动

javascript - 如何使用javascript从字符串中获取 anchor 标记的href值

html - 内联列表项框在包含中断词时向上移动

javascript - 如何使用jquery随机删除同一类的元素