Javascript通过递归函数传递变量

时间:2013-06-17 22:28:24

标签: javascript function

我正在尝试在Javascript中创建递归函数。但是为了正确循环我的XML文件,我试图传递从XML length获取的正确值并将其传递给setTimeout函数。 问题是setTimeoutsetTimeout('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); 
}

2 个答案:

答案 0 :(得分:2)

结帐How can I pass a parameter to a setTimeout() callback? - 基本上你需要将匿名函数传递给设置超时调用

setTimeout(function(){
    cvdXmlBubbleStart(nextIndex)
}, 3000); 

答案 1 :(得分:2)

使用匿名函数将起作用,因为它与nextIndex共享相同的范围。

setTimeout(function(){cvdXmlBubbleStart(nextIndex);}, 3000); 

当前代码不适合您的原因是因为当您在setTimeout函数中使用字符串时,它会使用Function构造函数基于以下内容创建function传递的字符串(类似于使用eval并且不是最佳实践)。更糟糕的是,使用Function创建的函数不会与创建它的位置共享相同的范围,因此无法访问nextIndex

相关问题