JavaScript onClick event - HTML table

后端 未结 3 1185
抹茶落季
抹茶落季 2021-02-05 11:30

I\'m learning JavaScript and recently I have been experimenting with Mouse events, trying to understand how they work.



    

        
3条回答
  •  后悔当初
    2021-02-05 12:11

    Instead of using getElementById, we could use .querySelectorAll to retrieve all the table dimensions AKA cells. After which, we can execute a single loop (Although please note that in the back end of JS, there will still be a loop executed to retrieve table cells.). First, let's create the action to be carried out upon clicking a cell:

    function tableText() {
        alert(this.innerHTML);
    }
    

    Let's retrieve all the cells with querySelectorAll method:

    var cells = document.querySelectorAll("td")
    

    Place the event listener to each and every cell:

    for (var i = 0; i < cells.length; i++)
        cells[i].addEventListener("click", tableText)
    }
    

    Complete code:

    function tableText() {
      alert(this.innerHTML);
    }
    
    var cells = document.querySelectorAll("td")
    
    for (var i = 0; i < cells.length; i++){
      cells[i].addEventListener("click", tableText)
    }
    

提交回复
热议问题