2

我在我的网站上使用基于jQuery 的记忆游戏。您可以随时重新开始游戏。效果很好。现在我完成了一场比赛,然后我再次点击播放。如果我点击重新启动它不再起作用。为什么以及如何解决?

这是一个小提琴

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>
4

1 回答 1

2

每当您单击此行时,您都在替换#restart元素:#play-again

info.html('Memory Game, click to reveal images. <a id="restart" href="#">Restart</a>');

这意味着#restart元素的单击处理程序不再附加到新元素。

您应该使用委托事件处理程序将处理程序附加到始终存在于 DOM 中的祖先元素.on()

info.on('click', '#restart', function(e)
{
    game.slashcMemoryGame('restart'); // restart game
});

小提琴

我用#restart委托事件处理程序替换了元素的直接绑定事件处理程序。这是额外阅读的参考:直接和委托事件。基本上,您只能将事件处理程序绑定到当前在 DOM 中的元素,并且:

委托事件的优点是它们可以处理来自以后添加到文档的后代元素的事件。

于 2012-08-28T23:25:49.383 回答