mardi 26 mai 2020

Javascript how to change color of button when click it?

I am new to Javascript. I want to create a 15X15 table full of buttons and change the color of the button to red when clicking each one. The table is fine but the color is not working.

function createTable(){
    var table = document.createElement('table');
    for(var x = 0; x < 15; x++) {
        var row = table.insertRow();
        for(var y = 0; y < 15; y++) {
            var cell = row.insertCell();
            var button = cell.appendChild(document.createElement('button'));
            var buttID = String('butt' + '_' + x + '_' + y);
            button.setAttribute('id', 'buttID');
            button.setAttribute('onclick', 'mark()');
        }
    }
    document.getElementById('puzzle').appendChild(table);
}

function mark(){
    document.getElementById('buttID').style.color = "red";
}

I am not sure if the button.setAttribute is wrong. I also tried the following way, but the entire table just disappears this time. Any ideas about that?

button.onclick = mark();

Maybe the way I create id for every cell is wrong? I am not sure about that.




Aucun commentaire:

Enregistrer un commentaire