[英]Event handler cannot watch for elements injected into HTML after document loads
I'm writing an application in Javascript. 我正在用Javascript编写应用程序。 Without going into too much detail, I have a game with a board (which is actually just an HTML table).
无需赘述,我有一个带有棋盘的游戏(实际上只是一个HTML表)。 The user interacts with the board by clicking on s, so I have a click event listener in my $(document).ready().
用户通过单击s与面板交互,因此我的$ {document).ready()中有一个click事件监听器。 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 .
事件处理程序通过更改几个变量/对象/等的状态,然后调用layoutBoard来更新开发板,layoutBoard读取所有这些对象的状态并填充。
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. 我遇到的问题是事件处理程序未监视新事件中的s,这意味着不再检测到click事件。 How can I direct the event handler to the new s or otherwise continue to detect clicks on the board?
如何将事件处理程序定向到new,否则如何继续检测板上的点击? 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 使用它来绑定您的动态事件处理程序
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.