jQuery没有监听动态生成的元素的点击

tom*_*tom 0 javascript jquery

因此,在我长达几个月的学习JavaScript的过程中,我终于坐下来建造了扫雷.作为奖励,它确实有效!(呃,第一次).

问题是,如果我清除我的电路板然后再动态生成新的游戏板,我的jQuery点击监听器都不会再工作了.游戏适用于第一个文档加载,但点击后不会注册.

完整的jfiddle: http ://jsfiddle.net/3w5zm64y/

与此问题相关的部分:

的index.html

<table class="gameBoard"></table> //the game board is dynamically generated inside of this table
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

问题:

    $(document).ready(function(){
    ....
    //right click check
        $(".left").find('td').on('mousedown',function(e){
          if( e.button == 2 ) {
             alert('**now this doesn't work!**');
          } 
        }
Run Code Online (Sandbox Code Playgroud)

我已经查看了我在SO和其他地方可以找到的所有相关问题.根据这个建议,我已经测试了下面的代码但是在重新生成我的表之后也没有用

$(document).ready(function(){
....
//right click check
    $(".left").on('mousedown','td',function(e){
Run Code Online (Sandbox Code Playgroud)

Yaj*_*aje 5

你必须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'));
      }
Run Code Online (Sandbox Code Playgroud)

这样它也可以用于生成的元素

DEMO

注意:

至于代码和性能优化,请参考@cyk关于事件性能的评论