-5

I have the following loop for a series of similar click events in jQuery. Everything works fine except for the last line below with the comment. How can I make each loop iteration call these functions respectively: step1(), step2(), step3(), etc.?

for (i = 0; i < 7; i++) {

    $("#stepbox" + i).click(function(){
    $("#step" + i).show();                     
    $("#stepswrapper section").not("#step" + i).hide();
    $("#stepbox" + i).addClass("stepboxactive");
    $("#stepboxmain div").not("#stepbox" + i).removeClass("stepboxactive");
    step + i(); // I'm stuck here. This doesn't work to create the function calls step1(), step2(), etc.
    });

}
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
Dan Oliv
  • 1
  • 4

2 Answers2

2

Assuming your functions are defined in the global context:

for (i = 0; i < 7; i++) {

    $("#stepbox" + i).click(function(){
        $("#step" + i).show();                     
        $("#stepswrapper section").not("#step" + i).hide();
        $("#stepbox" + i).addClass("stepboxactive");
        $("#stepboxmain div").not("#stepbox" + i).removeClass("stepboxactive");
        window["step" + i]();
    });
}
Dave
  • 10,748
  • 3
  • 43
  • 54
1

make an array of the step functions.

var step = [
  function () { /* step 0 */ },
  function () { /* step 1 */ },
  function () { /* step 2 */ }
  // ...
];
for (i = 0; i < 7; i++) {
    $("#stepbox" + i).click(function(){
        $("#step" + i).show();                     
        $("#stepswrapper section").not("#step" + i).hide();
        $("#stepbox" + i).addClass("stepboxactive");
        $("#stepboxmain div").not("#stepbox" + i).removeClass("stepboxactive");
        step[i]();
    });
}
Aleuck
  • 294
  • 1
  • 12
  • @dave I tried both approaches but they didn't work. Here's how my code is structured: $(document).ready(function(){ $("#stepbox1").click(function(){ $("#step1").show(); $("#stepswrapper section").not("#step1").hide(); $("#stepbox1").addClass("stepboxactive"); $("#stepboxmain div").not("#stepbox1").removeClass("stepboxactive"); step1(); }); // ...Plus another three of these click functions. And then: function step1() { // Stuff here } // ...Plus another three of these functions called from the buttons }); – Dan Oliv Apr 11 '15 at 00:04