Change color on my javascript table using jQuery?

I have two input fields for placing in height and width and a button for creating a table with Javascript. Now I want the color in each cell to change when I hang over them. Preferably with jQuery.

    function createTable(inRows, inCols) {
       var inRows = document.getElementById('height').value;
       var inCols = document.getElementById('length').value;

       var body = document.getElementsByTagName("body")[0];

           var tbl = document.createElement("table");
           var tblBody = document.createElement("tbody");

            for (var i = 0; i < inRows; i++) {
                var row = document.createElement("tr");

            for (var j = 0; j < inCols; j++) {
                var cell = document.createElement("td");
                row.appendChild(cell);
            }

            tblBody.appendChild(row);
        }

        tbl.appendChild(tblBody);
        body.appendChild(tbl);
    }   

$(document).ready(function() {
    $('td').hover(function() {
        $(this).addClass('black');
    });
});

In my weak beginner minds, this looks right. But .. he is not. I'm on the right track. And how to do it?

+4
source share
2 answers

, . createTable. mouseenter mouseleave, , (fiddle).

. , , ( ) , . , o , .

 function createTable(inRows, inCols) {
       var inRows = document.getElementById('height').value;
       var inCols = document.getElementById('length').value;

       var body = document.getElementsByTagName("body")[0];

       var tbl = document.createElement("table");
       var tblBody = document.createElement("tbody");

       for (var i = 0; i < inRows; i++) {
           var row = document.createElement("tr");

           for (var j = 0; j < inCols; j++) {
               var cell = document.createElement("td");
               row.appendChild(cell);
           }

           tblBody.appendChild(row);
       }

       tbl.appendChild(tblBody);
       // appends <table> into <body>
       body.appendChild(tbl);

       $(tbl).on('mouseenter', 'td', function () {
           $(this).addClass('black');
       });

       $(tbl).on('mouseleave', 'td', function () {
           $(this).removeClass('black');
       });
   }
+1

, CSS , , ? , CSS :

td:hover {background: black;}
+2

Source: https://habr.com/ru/post/1606157/


All Articles