简体   繁体   中英

Event handler cannot watch for elements injected into HTML after document loads

I'm writing an application in Javascript. Without going into too much detail, I have a game with a board (which is actually just an HTML table). The user interacts with the board by clicking on s, so I have a click event listener in my $(document).ready(). The event handler updates the board by changing the state of several variables/objects/etc and then calling layoutBoard, which reads the state of all those objects and populates the .

The problem I'm having is that the s in the new aren't being watched by my event handler, meaning click events are no longer detected. How can I direct the event handler to the new s or otherwise continue to detect clicks on the board? Here's my code:

$(document).ready(function(){
    layoutBoard();
    $("td").click(
        function() {
            movePiece($(this));
        }
    );
});

function movePiece(clickedCell){
    //do stuff
    layoutBoard();
}

function layoutBoard(){
    $("#board").empty();
    //recreate board and new <td>s
}

use on event delegation

$(document).on("click","td",function(){
     movePiece($(this));
});

it is better if you delegate to the closest static parent container...

like

$('#tableID').on("click","td",function(){
     movePiece($(this));
});
$("body").on("click", "td", function() {
    movePiece($(this));
})

Use this to bind your dynamic event handler

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