简体   繁体   中英

Table cell event listener

I have a while stuck with this code and don't know what's wrong! this jQuery code function is for a single web page application of a Game. I need to change a table cell background-color by clicking on it but it doesn't work:

$("document").ready(function() {
    var y, x, cellColor;
    //console.log("tata");

    $("#sizePicker").submit(function(event) {
        event.preventDefault();
    });

    $('input[type="submit"]').click(function makeGrid(y, x) {
        y = Number($("#inputHeight").val());
        x = Number($("#inputWeight").val());
        $("#pixelCanvas tr").remove();
        for (i = 0; i < y; i++) {
            $("#pixelCanvas").append("<tr class='vertical'></tr>");
        }
        for (j = 0; j < x; j++) {
            $(".vertical").append("<td class='cell' ></td>");
        }
        $("#pixelCanvas tr td").css("background-color", "red");
    });

    $("#pixelCanvas tr td").click(function() {
        $(this).css("background-color", "blue");
    });
});

I think the problem is that when you bind a click event to the table cells, those cells are not created yet. Try binding a click event to the body and use the "#pixelCanvas tr td" selector to filter event consumers: instead of $("#pixelCanvas tr td").click write the following:

$("body").on("click", "#pixelCanvas tr td", function() {
    $(this).css("background-color", "blue");
});

The problem is that the elements have not been created until the click of 'input[type="submit"]' is done. Move the binding of the click of the cells into the click handler of 'input[type="submit"]':

$("document").ready(function() {
    var y, x, cellColor;
    //console.log("tata");

    $("#sizePicker").submit(function(event) {
        event.preventDefault();
    });

    $('input[type="submit"]').click(function makeGrid(y, x) {
        y = Number($("#inputHeight").val());
        x = Number($("#inputWeight").val());
        $("#pixelCanvas tr").remove();
        for (i = 0; i < y; i++) {
            $("#pixelCanvas").append("<tr class='vertical'></tr>");
        }
        for (j = 0; j < x; j++) {
            $(".vertical").append("<td class='cell' ></td>");
        }
        $("#pixelCanvas tr td").css("background-color", "red");

        $("#pixelCanvas tr td").click(function() {
           $(this).css("background-color", "blue");
        });
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM