我正在使用 DOM,但遇到了一些奇怪的事情。以下是将事件处理程序添加到 jQuery 对象的代码:
function randomizeTiles() {
var $tiles = $("#letterbox a");
$tiles.each(function() {
var index = Math.floor(Math.random() * 100);
var letter = frequencyTable[index];
$(this).attr("class", $(this).attr("class") + " l" + letter);
$(this).on("click.add", addLetter);
});
}
该代码添加了事件处理程序 addLetter,其中包含在事件处理程序完成调用后删除事件处理程序的代码:
function addLetter() {
var tileClasses = $(this).attr("class").split(" ");
var letterClass = tileClasses[2];
var tileLetter = letterClass.substring(1,2);
var $currentWordDiv = $("#currentWord");
if ($currentWordDiv.children().length === 0) {
var $p = $("<p></p>");
$currentWordDiv.append($p);
$p.append(tileLetter);
var $submitDiv = $("#submit");
var a = $submitDiv.children(":first-child");
a.on("click.sub", submitWord);
}
else {
var p = $currentWordDiv.children(":first-child");
//Get text value of the p element
var letterText = p.text();
//Adds the tile letter to current letter(s) in letterText
letterText += tileLetter;
//Replaces the current text with the updated text
p.text(letterText);
}
$(this).attr("class", $(this).attr("class") + " disabled");
$(this).off("click.add");
}
尽管它在大多数情况下都有效,但有时事件处理程序尽管被删除,但仍会触发。这个问题有什么解决办法吗?