adding onClick event to JavaScript for loop

前端 未结 1 1230
挽巷
挽巷 2021-01-25 23:36

What I am trying to do is to create an App in which there are 26 boxes with ids case0, case1, case2 and so on. When clicked, these should add class \'black\' to respective item0

1条回答
  •  滥情空心
    2021-01-26 00:12

    The onclick function should get the ID of the element that was clicked. Then replace case with item to get the corresponding item, and pass that as an argument to clickCase().

    The reason only the last item is clickable is because you're rewriting document.getElementById("casePanel").innerHTML each time through the loop. This recreates all the elements, so all the previous elements no longer have their click handlers.

    You can use insertAdjacentHTML() to add HTML to an element without reparsing what it already contains.

    let num = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25];
    let guess = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25];
    let i, x;
    let arrayShuffle = function(arr) {
      let newPos, temp;
      for (let i = arr.length - 1; i > 0; i--) {
        newPos = Math.floor(Math.random() * i + 1);
        temp = arr[i],
          arr[i] = arr[newPos];
        arr[newPos] = temp;
      }
      return arr;
    };
    
    let numRandom = arrayShuffle(guess);
    suitCase();
    
    function suitCase() {
      for (x = 0; x < num.length; x++) {
        document.getElementById("casePanel").insertAdjacentHTML('beforeend', "
    " + num[x] + "
    "); document.getElementById('case' + numRandom[x]).onclick = function() { clickCase(this.id.replace('case', 'item')); } } }; function clickCase(id) { document.getElementById(id).classList.add('black'); }
    .black {
      background-color: blue;
    }

    This is a sample title for this nice suitcase casino

    • $.01
    • $1
    • $5
    • $10
    • $25
    • $50
    • $75
    • $100
    • $200
    • $300
    • $400
    • $500
    • $750
    • $1000
    • $5000
    • $10,000
    • $25,000
    • $50,000
    • $75,000
    • $100,000
    • $200,000
    • $300,000
    • $400,000
    • $500,000
    • $750,000
    • $1,000,000

    0 讨论(0)
提交回复
热议问题