防止jQuery中出现“过多的递归”错误

时间:2012-11-13 10:22:37

标签: javascript jquery loops if-statement recursion

修改**

我有点击事件

$('.next-question').click(function () {

    $('td').removeClass('highlight-problem');
    var r = rndWord;
    while (r == rndWord) {
        rndWord = Math.floor(Math.random() * (listOfWords.length));
    }
    $('td[data-word="' + listOfWords[rndWord].name + '"]').addClass('highlight-problem');
    $('td[data-word=' + word + ']').removeClass('wrong-letter').removeClass('wrong-word').removeClass('right-letter');
    var spellSpace = $('td[data-word=' + listOfWords[rndWord].name + ']').hasClass('right-word');
    if (spellSpace) {

        $('.next-question').trigger('click');

   } else {

        $("#hintSound").attr('src', listOfWords[rndWord].audio);
        hintSound.play();
        $("#hintPic").attr('src', listOfWords[rndWord].pic);
        $('#hintPic').show();
        $('#hintPicTitle').attr('title', listOfWords[rndWord].hint);
        $('#hintPicTitle').show();

    }

});

在控制台中进行调试时,它会显示too much recursion,这意味着此时它处于某种无限循环中。我认为这是因为trigger("click")声明中的if事件,因为我在网上看到了类似的内容。

基本上,我想说,如果给定的单词有right-word,那么继续(因此触发),否则...

还有其他方法可以写它不会崩溃吗?

这是一个小提琴:http://jsfiddle.net/Dxxmh/112/

说明:单击右侧的字母拼写网格中突出显示的区域(帮助您拼写单词的图像无法在小提琴中拼写,因此您必须使用控制台拼写它们,通过查找td)

4 个答案:

答案 0 :(得分:2)

.trigger('click')将再次调用侦听器。您是否打算仅在这种情况下关注链接?在这种情况下,您可以在return false方案中else

答案 1 :(得分:2)

这不是jQuery问题:您在处理程序中手动触发相同的事件:

 $('.next-question').trigger('click');

现在,如果你不小心,这将导致无限循环。修复此问题的最佳方法是 not 通过第二次触发事件来调用处理程序,但是通过使用函数名称调用它:

 $('.next-question').click(function callMe(event)
 {
      //replace: $('.next-question').trigger('click');
      //with this:
      if (spellSpace && event)
      {//also check if the event has been passed
          callMe.apply(this,[]);//don't pass event for recursive call
      }
 });

答案 2 :(得分:2)

我会做这样的事情:

if (spellSpace) {
            if(score.right != 4)
                $('.next-question').trigger('click');

我觉得if(score.right == 4)意味着游戏结束。结束后 - 你根本就没有语言(或者根本就没有“正确”的话,不确定),这就是它永远不会停止的原因。它只是永远触发click而不是停止做任何事情并等待用户点击Restart按钮。

我猜这种情况还不够。不确定如何计算和处理错误单词的数量。但它应该足够前进并根据您的程序逻辑构建正确的条件。您启动的任何递归(并且使用触发器(“click”)启动它)必须具有停止条件。

答案 3 :(得分:0)

尝试使用它:

$('.next-question').click(function (event) {
     event.preventDefault();
 });