【问题标题】:Using jquery to toggle div when parent div is visible当父div可见时使用jquery切换div
【发布时间】:2013-11-15 06:35:12
【问题描述】:

我有几个具有相同类的父 div 标签,其中包含两个子 div,其中一个是隐藏的。一次只显示一个父级。我有一个按钮,它通过显示下一个并隐藏上一个来一次移动通过父级。第二个按钮必须在可见时切换父级的两个子级 div,但它仅适用于第一个父级而不适用于其他父级.. 请在下面提供示例 html.. 非常感谢帮助.. 谢谢

<div class="parent"   >
<div id="child1">  text  </div> 
<div id="child2" style="display:none">  text  </div> 
</div>
<div class="parent" style="display:none"  >
<div id="child1">  text  </div> 
<div id="child2" style="display:none">  text  </div> 
</div>
<div class="parent"  style="display:none" >
<div id="child1">  text  </div> 
<div id="child2" style="display:none">  text  </div> 
</div>

通过 parent 移动的脚本: $(函数 () {

$(".parent:first").fadeIn(); // show first step

$("#next-step").val('Continue');
$("#back-step").hide().click(function () {
    var $step = $(".parent:visible"); 
    if ($step.prev().hasClass("parent")) { // is there any previous step?
        $step.hide().prev().fadeIn();  // show it and hide current step
    }
});

$("#next-step").click(function () {
    var $step = $(".parent:visible"); 
    if ($step.next().hasClass("parent")) { 
        $step.hide().next().fadeIn();  
        $("#back-step").show();   // recall to show backStep button 
    }
  else { // this is last step, submit form
        //$("#next-step").hide();
        $("form").submit();
    }

});

});

用于为每个当前可见的父 div 切换子级的按钮脚本

$('.txtFlip').on('click', function(event) {
 $('.parent:visible > #child1').slideToggle();
 $('.parent:visible > #child2').slideToggle();
});

我现在的问题是为每个当前可见的父级切换 child1 和 child2 的脚本。它仅适用于第一个父母,但不适用于其他父母。请帮忙...

谢谢......

【问题讨论】:

  • 分享你当前的脚本。如果可能的话,jsfiddle 会很棒jsfiddle.net
  • 它是def的原因。不起作用是您有多个具有相同 ID 的 div。 ID 是唯一的,因此只能有一个 ID 相同。
  • 能否请您提供您的 js 代码,以便我确定问题所在
  • 亲爱的大家,很抱歉我离开了一段时间。我仍然没有解决我的问题。我可以在父 div 中移动,但在不同父 div 中移动时无法切换 child1 和 child2。请在上面找到我的脚本的快照:

标签: javascript jquery html


【解决方案1】:

您可以使用 jQuery 的 :visible 选择器来选择当前可见的元素并根据它进行切换。

bindLoopThrough = function($button, initial_selector){
    // Define a function that will apply for both sets of buttons,
    // because they have similar functionality
    $button.on("click", function(){
        var $current = $(initial_selector),
            $next = $current.next();
        if($next.length===0){
            $next = $current.siblings().eq(0); // Reached end, get first.
        }
        $current.hide();
        $next.show();
    });
}

bindLoopThrough($("#button1"), ".parent:visible");
bindLoopThrough($("#button2"), ".parent:visible .child:visible");

【讨论】:

    猜你喜欢
    • 2014-03-02
    • 1970-01-01
    • 1970-01-01
    • 2010-11-21
    • 2015-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多