开发者

setInterval can't access variable?

I have a JavaScript function named showchild(pgid). I have called function on document ready...

$(document).ready(function()
{
     var pgid = $('#hiddenuserkey').val();
    //al开发者_开发问答ert(pgid);
     showchild(pgid);
     setInterval("showchild(pgid)",1000);
});


You are using it in the worst possible way - passing a string.

Use the following code instead:

setInterval(function() {
    showchild(pgid);
}, 1000);

When passing a string, it will be evaluated in the global context without having access to any non-global variables. By passing a function (the preferred way) all accessible variables are preserved in the function's closure so pgid is defined inside that function when it's called.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜