开发者

setInterval can't access variable?

开发者 https://www.devze.com 2023-04-03 21:47 出处:网络
I have a JavaScript function named showchild(pgid). I have called function on document ready... $(document).ready(function()

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

精彩评论

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

关注公众号