I don't know what to do without jquery.



  • I need her to be black on the cell in the table, 'cause I somehow managed to make sure that the red table painted the cells, but the table that was generated after the click page was down.

    var html = '<table><tr><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td></tr></table>',
      td = document.querySelector("td");
    // document.querySelector('td').onclick = function() {
    //   this.style.background = "black";
    

    // };

    for (var i = 0; i < td.length; i++) {

    td[i].onclick = function() {
    this.style.background = "black";

    };
    }

    document.querySelector('#but').onclick = function() {
    document.querySelector('#new-table').innerHTML = html;

    };

    td {
    padding: 25px;
    background: red;
    cursor: pointer;
    }
    #new-table td {
    background: green;
    }
    <button id="but">Создать новую табл</button>
    <table>
    <tr>
    <td></td>
    <td></td>
    <td></td>
    </tr>
    <tr>
    <td></td>
    <td></td>
    <td></td>
    </tr>
    <tr>
    <td></td>
    <td></td>
    <td></td>
    </tr>
    </table>
    <div id="new-table"></div>



  • After adding the table, new boxes need to be added the processors, so that the code can be added to the function, eventually it can be approximately as follows:

    var html = '<table><tr><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td></tr></table>';
    

    function addHandlers(table) {
    var tds = table.querySelectorAll("td");
    for (var i = 0; i < tds.length; i++) {

    tds[i].onclick = function() {
      this.style.background = "black";
    
    };
    

    }
    }

    addHandlers(document.querySelector('table'));

    document.querySelector('#but').onclick = function() {
    var table = document.querySelector('#new-table')
    table.innerHTML = html;
    addHandlers(table);

    };

    td {
    padding: 25px;
    background: red;
    cursor: pointer;
    }
    #new-table td {
    background: green;
    }
    <button id="but">Создать новую табл</button>
    <table>
    <tr>
    <td></td>
    <td></td>
    <td></td>
    </tr>
    <tr>
    <td></td>
    <td></td>
    <td></td>
    </tr>
    <tr>
    <td></td>
    <td></td>
    <td></td>
    </tr>
    </table>
    <div id="new-table"></div>


Log in to reply
 


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2