在我的resetTable函数中,在创建新表后,在最底部调用我的hover()函数,这样便可以使用草图。但是,由于hover()函数包括更改表格单元格的背景色,因此我需要将其关闭,以便trail()函数可以更改表格单元格的不透明度。

我将resetTableTrail函数设置为调用原始resetTable()函数的位置,然后应该将hover()函数关闭,并允许trail()函数接管,但这似乎不是案子。

这是一个现场演示:http://codepen.io/hgducharme/pen/bmyGc?editors=001

这是我的代码的相关部分:

$(function() {
  buildTable(16);
  hover();
  resetTable();
  trail();
  randomColorHover();
  resetTableTrail();
});



// Hover Function To Add Colors
function hover() {
  $('td').hover(function() {
    $(this).css('background-color', 'rgb(90,188,215)');
  },

  function() {
    $(this).css('background-color', 'rgb(90,188,215)');
  });
};


// Rebuilds Table When Button Is Clicked
function resetTable() {
  $('button').on('click', function() {

    var choice = prompt("How many columns and rows would you like? Please pick a number between (1 & 64).", "16");

    if (choice < 1 || choice > 64) {
      alert("That was not a valid entry, please specify a number between (1 & 64)");
      return null;
    }

    else {
      var resetColor = $('td').css('background-color', 'rgb(215,215,215)');
      var removeTable = $('table').remove();
      buildTable(choice);
      $('td').on("click", hover() );
    }
  });
}

// If the hover call is in the original resetTable function
// Then it doesn't allow for the trail mode to properly run
// So I created a new function that allows for the trail mode
// To run properly, and also allows for the normal button
// To reset the grid and then call the hover function
// When the grid resets
function resetTableTrail() {
  $('#trail').click(function() {

    resetTable();

    $('td').off("click", hover() );

    trail();

  });
}


// Creates Trail
function trail() {
  $("#trail").click(function() {
    $('td').hover(function() {
      $(this).css('opacity', '0');
    },

    function() {
      $(this).fadeTo('slow', 1);
    });
  });
};

最佳答案

off()应参考on()附加的功能。

所以这

$('td').off("click", hover() );


是错误的,因为您的悬停不返回任何功能。

您最好在这里使用命名空间事件。设置:

.on('click.somename', function() {} )


并删除:

.off('click.somename'); // note - does not need function reference here.


但是我个人将只使用一个附加到表本身的处理程序:

$('table').on('click','td', function() { ... })


在这种情况下,您不需要在表操作上添加/删除处理程序。

10-05 20:42
查看更多