[英]jQuery not listening for clicks on dynamically generated elements
因此,在我為期幾個月的學習JavaScript的探索中,我終於坐下來建造了Minesweeper。 作為獎勵,它實際上有效! (嗯,第一次。)。
問題是,如果我清除我的棋盤,然后再次動態生成新的游戲棋盤,則我的jQuery單擊偵聽器將不再起作用。 游戲在第一個文檔加載時工作,但單擊后不注冊。
完整的jfiddle: http : //jsfiddle.net/3w5zm64y/
與該問題有關的部分:
index.html
<table class="gameBoard"></table> //the game board is dynamically generated inside of this table
JS代碼
$(document).ready(function(){
....
//right click check
$(".left").find('td').on('mousedown',function(e){
if( e.button == 2 ) {
alert('this works only on the first page load');
}
}
$('.gameBoard').text(''); //this is where I clear out everything within the gameBoard table
draw_board(numRows,numCols); //this method puts everything back into the gameBoard table
問題:
$(document).ready(function(){
....
//right click check
$(".left").find('td').on('mousedown',function(e){
if( e.button == 2 ) {
alert('**now this doesn't work!**');
}
}
我仔細研究了所有可以在SO和其他地方找到的相關問題。 根據該建議,我已經測試了以下代碼,但在重新生成表后也無法正常工作
$(document).ready(function(){
....
//right click check
$(".left").on('mousedown','td',function(e){
您必須使用document
作為選擇器
像這樣 :
$(document).on('mousedown','.left td',function(e){
if( e.button == 2 ) {
if($(this).hasClass('blank')){
$(this).removeClass('blank');
$(this).addClass('flag');
$(this).text('');
$(this).append('<img src="http://www.chezpoor.com/minesweeper/images/bombflagged.gif">'); //add flag if it's blank
} else if($(this).hasClass('flag')) {
$(this).removeClass('flag');
$(this).addClass('blank');
$(this).text('');
$(this).append('<img src="http://www.chezpoor.com/minesweeper/images/blank.gif">'); //back to blank
}
}
});
//left click check
$(document).on('mousedown','.left td',function(e){
if( e.button === 0 ) {
checkCell($(this).attr('id'));
}
這樣,它將與生成的元素一起使用
注意事項 :
關於代碼和性能優化,請參閱下面有關事件性能的@cyk注釋
重新創建面板時,將銷毀所有偵聽器。
將聽眾放在畫板的末端,效果很好。
http://jsfiddle.net/3w5zm64y/4/
function draw_board(x,y){
...
createListeners();
}
$(document).ready(function(){
..
// init functions
draw_board(numRows,numCols);
});
function createListeners() {
// add listeners here
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.