我正在使用jQuery Based Memory Game在我的网站上。您可以随时重新开始游戏。效果很好。现在我完成了游戏,然后我点击“再玩一次”。如果我点击重新启动,它就不再起作用了。为什么以及如何修复它?
这是一个fiddle .
JS:
// this script shows how you can get info about the game
var game = jQuery('div.slashc-memory-game'); // get the game
var info = jQuery('p#info').find('span'); // get the info box
var restart = jQuery('a#restart').css('visibility', 'visible'); // get the play again link
var playAgain = jQuery('a#play-again').css('visibility', 'hidden'); // get the play again link
// format time like hh:mm:ss
var formatTime = function(s)
{
var h = parseInt(s / 3600), m = parseInt((s - h * 3600) / 60); s = s % 60;
return (h < 10 ? '0' + h : h) + ':' + (m < 10 ? '0' + m : m) + ':' + (s < 10 ? '0' + s : s);
}
// listen for game 'done' event
game.bind('done', function(e)
{
// show basic stats
var stats = game.slashcMemoryGame('getStats');
info.html('Success ! Number of clicks : ' + stats.numClicks + ', elapsed time : ' + formatTime(parseInt(stats.time / 1000)) + '.');
playAgain.css('visibility', 'visible'); // show link
restart.css('visibility', 'hidden'); // show link
});
// Restart action
restart.click(function(e)
{
game.slashcMemoryGame('restart'); // restart game
});
// play again action
playAgain.click(function(e)
{
playAgain.css('visibility', 'hidden'); // hide link
info.html('Memory Game, click to reveal images. <a id="restart" href="#">Restart</a>'); // reset text
game.slashcMemoryGame('restart'); // restart game
e.preventDefault();
});
HTML:
<p id="info"><span>Memory Game, click to reveal images. <a id="restart" href="#">Restart</a></span> <a id="play-again" href="#">Play Again</a></p>
最佳答案
每当您在此行单击 #play-again
时,您就会替换 #restart
元素:
info.html('Memory Game, click to reveal images. <a id="restart" href="#">Restart</a>');
这意味着 #restart
元素的点击处理程序不再附加到新元素。
您应该使用委托(delegate)事件处理程序将处理程序附加到始终存在于 DOM 中的祖先元素 .on()
:
info.on('click', '#restart', function(e)
{
game.slashcMemoryGame('restart'); // restart game
});
我用委托(delegate)事件处理程序替换了#restart
元素的直接绑定(bind)事件处理程序。以下是额外阅读的引用:Direct and delegated events 。基本上,您只能将事件处理程序绑定(bind)到 DOM 中当前的元素,并且:
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.
关于javascript - 重新启动游戏 jQuery 函数不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12168757/