我试图在Javascript中创建一个递归函数。但是为了正确循环我的XML文件,我试图传递从XML length取得的正确值,并将其传递给setTimeout函数。问题是setTimeout(setTimeout('cvdXmlBubbleStart(nextIndex)', 3000);)函数未获取nextIndex的值,并认为它是undefined。我确定我做错了。jQuery(document).ready(function($) {cvdXmlBubbleStart('0');});function cvdXmlBubbleStart(nextIndex) { $.ajax({ url: "cross_video_day/xml/broadcasted.xml", dataType: "xml", cache: false, success: function(d) { broadcastedXML = d; cvdBubbleXmlProcess(nextIndex); } });}function cvdBubbleXmlProcess(nextIndex) { var d = broadcastedXML;//console.log(nextIndex); var length = $(d).find('tweet').length; if((nextIndex + 1) < length) { nextIndex = length - 1; $(d).find('tweet').eq(nextIndex).each(function(idx) { var cvdIndexId = $(this).find("index"); var cvdTweetAuthor = $(this).find("author").text(); var cvdTweetDescription = $(this).find("description").text(); if (cvdTweetAuthor === "Animator") { $('#cvd_bubble_left').html(''); obj = $('#cvd_bubble_left').append(makeCvdBubbleAnimator(cvdIndexId, cvdTweetAuthor, cvdTweetDescription)); obj.fitText(7.4); $('#cvd_bubble_right').html(''); setTimeout('$(\'#cvd_bubble_left\').html(\'\')', 3000); } else { $('#cvd_bubble_right').html(''); obj = $('#cvd_bubble_right').append(makeCvdBubble(cvdIndexId, cvdTweetAuthor, cvdTweetDescription)); obj.fitText(7.4); $('#cvd_bubble_left').html(''); setTimeout('$(\'#cvd_bubble_right\').html(\'\')', 3000); } }); }else{ $('#cvd_bubble_left').html(''); $('#cvd_bubble_right').html(''); } //broadcastedXMLIndex++; setTimeout('cvdXmlBubbleStart(nextIndex)', 3000);} 最佳答案 使用匿名函数将起作用,因为它与nextIndex具有相同的作用域。setTimeout(function(){cvdXmlBubbleStart(nextIndex);}, 3000);当前代码对您不起作用的原因是,当您在setTimeout函数内部使用字符串时,它会使用Function构造函数根据传递的字符串创建function(类似于使用,而不是最佳做法)。更糟糕的是,使用eval创建的函数将不具有与其创建位置相同的作用域,因此无法访问Function。
09-25 19:54