簡體   English   中英

當父div可見時使用jquery切換div

[英]Using jquery to toggle div when parent div is visible

我有幾個具有相同類的父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>

通過父級移動的腳本:$(function(){

$(".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的腳本。 它僅適用於第一個父母,而不適用於其余父母。 幫助...

謝謝......

您可以使用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");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM