JavaScript onClick event - HTML table

后端 未结 3 1189
抹茶落季
抹茶落季 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:02
    var table = document.getElementById("tableID");
    if (table != null) {
        for (var i = 0; i < table.rows.length; i++) {
            for (var j = 0; j < table.rows[i].cells.length; j++)
            table.rows[i].cells[j].onclick = function () {
                tableText(this);
            };
        }
    }
    
    function tableText(tableCell) {
        alert(tableCell.innerHTML);
    }
    

    is an example of what you could do. DEMO

    0 讨论(0)
  • 2021-02-05 12:07

    Just insert onclick into each <td> of the table and if the cell's name were example, you could do something similar to this:

    <td onclick="alert('You are clicking on the cell EXAMPLE')">
    
    0 讨论(0)
  • 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)
    }
    
    0 讨论(0)
提交回复
热议问题