重启游戏jQuery功能不起作用

时间:2012-08-28 23:03:26

标签: javascript jquery

我在我的网站上使用了jQuery Based Memory Game。您可以随时重启游戏。效果很好。现在我完成了一场比赛,然后我再次点击Play。如果我点击重启它不再有效。为什么以及如何解决?

这是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>

1 个答案:

答案 0 :(得分:2)

只要您在此行点击#restart,就会替换#play-again元素:

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

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

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

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

Fiddle

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

  

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