[英]Preventing “too much recursion” error in jQuery
编辑**
我有这个点击事件
$('.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
这意味着它在这一点上处于某种无限循环中。 我认为这是因为if
语句中的trigger("click")
事件,因为我在网上看到了类似的东西。
基本上,我想说,如果给定的单词有right-word
然后继续(因此触发),否则......
还有另一种方法来写它不会崩溃吗?
这是一个小提琴: http : //jsfiddle.net/Dxxmh/112/
说明:单击右侧的字母拼写网格中突出显示的区域(帮助您拼写单词的图像不适用于小提琴,因此您必须使用控制台拼写它们,通过查找td)
.trigger('click')
将再次调用侦听器。 您是否打算仅在这种情况下关注链接? 在这种情况下,您可以在else
方案中return false
。
这不是jQuery问题:您从处理程序中手动触发相同的事件:
$('.next-question').trigger('click');
现在,如果你不小心,这将导致无限循环。 解决此问题的最佳方法是不是通过第二次触发事件来调用处理程序,而是通过使用函数名称调用它:
$('.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
}
});
我会做这样的事情:
if (spellSpace) {
if(score.right != 4)
$('.next-question').trigger('click');
我觉得if(score.right == 4)
意味着游戏结束。 结束后 - 你根本就没有语言(或者根本就没有“正确”的话,不确定),这就是它永远不会停止的原因。 它只是永远触发click而不是停止做任何事情并等待用户单击Restart按钮。
我猜这种情况还不够。 不确定如何计算和处理错误单词的数量。 但它应该足够前进并根据您的程序逻辑构建正确的条件。 您启动的任何递归(并且使用触发器(“click”)启动它)必须具有停止条件。
试着用这个:
$('.next-question').click(function (event) {
event.preventDefault();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.