简体   繁体   中英

How to determine which element has been clicked using a for statement and array

I have 8 boxes that the user can select, if they select box 1 - it should alert that box 1 has been selected. The same applies to all 8 boxes. Right now, I'm running a for loop at an interval of 1/10th of a second, which should check which box is being clicked, and then output the alert based on the switch statement.

When you run the code, it alerts that box 8 has always being selected, and I can't figure out, how to select the box

  • The boxes are empty divs set in the HTML document, with the id referenced in the array

EDIT: The clearInterval(interval); works in it's current position, but on every click outputs an error

"Uncaught ReferenceError: interval is not defined"

^ Any ideas?

Page Load:

$(function() { //On page load
    var interval = setInterval(buttonClick, 100);
});

Button click function

function buttonClick() {

    //INITIALIZING ARRAY
    var displayBox = [$("#boxOne-line-one"), $("#boxTwo-line-one"), $("#boxThree-line-one"), $("#boxFour-line-one"), $("#boxFive-line-one"), $("#boxSix-line-one"), $("#boxSeven-line-one"), $("#boxEight-line-one")];
    var slidePos = 0;

    for (let i = 0; i <= 7; i++) {
  (ii => {
    displayBox[ii].click(function() {
      slidePos = ii;
      console.log(slidePos);
      wbox(slidePos);
      clearInterval(interval);
    });
  })(i);
}
}

Switch statement function, "which box"

function wbox(slidePos) {
        switch(slidePos) {
        case 0:
        alert("BOX 1 SELECTED");
        break;

            case 1:
        alert("BOX 2 SELECTED");
        break;

        case 2:
        alert("BOX 3 SELECTED");
        break;

        case 3:
        alert("BOX 4 SELECTED");
        break;

        case 4:
        alert("BOX 5 SELECTED");
        break;

        case 5:
        alert("BOX 6 SELECTED");
        break;

        case 6:
        alert("BOX 7 SELECTED");
        break;

        case 7:
        alert("BOX 8 SELECTED");
        break;
    }
}

Actual: "BOX 8 SELECTED"
Expected: The correct box

You need to change your loop to avoid i being global:

for (let i = 0; i < 7; i++) {
  (ii => {
    displayBox[ii].click(function() {
      slidePos = ii;
      console.log(slidePos);
      wbox(slidePos);
      clearInterval(interval);
    });
  })(i);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM