2014-03-13 3 views
0

사이트에 주문 양식을 작성하고 주문 프로세스를 탐색하는 데 일부 js를 사용했습니다. 한 단계가 완료되면 사용자는 "다음"버튼을 클릭해야 다음 다양한 div는/숨기기 표시해야합니다 : 코드가 아주 ... 긴 당신이 볼 수 있듯이중첩 된 함수가있는 For 루프

$("#buttonShowStep2").click(function() { 
    $(this).hide("blind", 200); 
    $("#outerDivStep2").show("blind", 300, function() { 
     $('html, body').animate({ scrollTop: $(".scrollToHeading2").offset().top - 20 }); 
     document.getElementById("checkHeading1").className = "orderChecked"; 
    }); 
}); 

$("#buttonShowStep3").click(function() { 
    $(this).hide("blind", 200); 
    $("#outerDivStep3").show("blind", 300, function() { 
     $('html, body').animate({ scrollTop: $(".scrollToHeading3").offset().top - 20 }); 
     document.getElementById("checkHeading2").className = "orderChecked"; 
    }); 
}); 

$("#buttonShowStep4").click(function() { 
    $(this).hide("blind", 200); 
    $("#outerDivStep4").show("blind", 300, function() { 
     $('html, body').animate({ scrollTop: $(".scrollToHeading4").offset().top - 20 }); 
     document.getElementById("checkHeading3").className = "orderChecked"; 
    }); 
}); 

합니다. 나는 그것을 둘러싸 기 위해 for 루프를 약간 만들었다. 불행히도 작동하지 않습니다.

질문 : 복수 중첩 기능이있는 for 루프를 만들 수 있습니까? 당신의 도움을 주셔서 감사합니다!

for (var i = 2; i <= 4; i++) { 
    var buttonShowStep = "#buttonShowStep" + i; 
    var outerDivStep = "#outerDivStep" + i; 
    var scrollToHeading = ".scrollToHeading" + i; 
    var checkHeading = "#checkHeading" + i -1; 
     $(buttonShowStep).click(function() { 
      $(this).hide("blind", 200); 
      $(outerDivStep).show("blind", 300, function() { 
       $('html, body').animate({ scrollTop: $(scrollToHeading).offset().top - 20 }); 
       document.getElementById(checkHeading).className = "orderChecked"; 
      }); 
    }); 
}; 

답변

1

모든 버튼에

변경이있는 버튼과 같은 기능을 사용하여 팩터 :

$(".buttonShowStep").click(function() { 
    var self = $(this); 
    var step = self.data("step"); 
    if (step == 1) return; 
    var prevStep = step - 1; 
    self.hide("blind", 200); 
    $("#outerDivStep" + step).show("blind", 300, function() { 
     $('html, body').animate({ scrollTop: $(".scrollToHeading" + step).offset().top - 20 }); 
     document.getElementById("checkHeading" + prevStep).className = "orderChecked"; 
    }); 
}); 
+0

저에게 잘 맞습니다. 고마워요! – Alex

0
이 코드의 인클로저가

:

<a data-step="1" class="buttonShowStep"> 

을 그리고이 기능을 추가 부작용. 다음으로 변경 :

function ButtonShowStep(i) { 
    var buttonShowStep = "#buttonShowStep" + i; 
    var outerDivStep = "#outerDivStep" + i; 
    var scrollToHeading = ".scrollToHeading" + i; 
    var checkHeading = "#checkHeading" + i -1; 
    $(buttonShowStep).click(function() { 
     $(this).hide("blind", 200); 
     $(outerDivStep).show("blind", 300, function() { 
      $('html, body').animate({ scrollTop: $(scrollToHeading).offset().top - 20  }); 
      document.getElementById(checkHeading).className = "orderChecked"; 
     }); 
    }); 
} 

for (var i = 2; i <= 4; i++) { 
    ButtonShowStep(i); 
};