简体   繁体   English

如何使用for语句和数组确定哪个元素被点击

[英]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.我有 8 个用户可以选择的框,如果他们选择框 1 - 它应该提醒框 1 已被选中。 The same applies to all 8 boxes.这同样适用于所有 8 个盒子。 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.现在,我以 1/10 秒的间隔运行一个 for 循环,它应该检查正在单击哪个框,然后根据 switch 语句输出警报。

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当你运行代码时,它会提示框 8 一直被选中,我不知道如何选择框

  • The boxes are empty divs set in the HTML document, with the id referenced in the array这些框是在 HTML 文档中设置的空 div,在数组中引用了 id

EDIT: The clearInterval(interval);编辑:clearInterval(interval); works in it's current position, but on every click outputs an error在当前位置工作,但每次点击都会输出错误

"Uncaught ReferenceError: interval is not defined" “未捕获的 ReferenceError:间隔未定义”

^ 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" switch语句函数,“哪个框”

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"实际:“选择框 8”
Expected: The correct box预期:正确的框

You need to change your loop to avoid i being global:您需要更改循环以避免i成为全球性的:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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