访问 setInterval 中的内部函数

发布于 2024-08-31 09:40:18 字数 618 浏览 1 评论 0原文

(function($)
{
    $.fn.myPlugin = function(options)
    {
        var _this;
        var timer1;

        var foo = function(n)
        {
            if (timer1 != null) return; // in action
            timer1 = setInterval("bar("+n+")", 500);
        };

        var bar = function(n)
        {
            ...
            if ( ... ) clearInterval(timer1);
        };                      

        return this.each(function()
        {
            _this = $(this);
            _this.bind("click", function(){ foo(10); });            
        });
    }
})(jQuery);

这不起作用,因为“bar 未定义”。

(function($)
{
    $.fn.myPlugin = function(options)
    {
        var _this;
        var timer1;

        var foo = function(n)
        {
            if (timer1 != null) return; // in action
            timer1 = setInterval("bar("+n+")", 500);
        };

        var bar = function(n)
        {
            ...
            if ( ... ) clearInterval(timer1);
        };                      

        return this.each(function()
        {
            _this = $(this);
            _this.bind("click", function(){ foo(10); });            
        });
    }
})(jQuery);

This doesn't work because "bar is not defined."

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

送君千里 2024-09-07 09:40:18

您需要传递一个直接引用 bar 的函数,而不是字符串,因此不要这样做:

setInterval("bar("+n+")", 500);

这样做:

setInterval(function() { bar(n) }, 500);

您可以在此处看到此操作

此外,您需要接受问题才能获得未来的答案,您可以通过单击帮助您解决问题的答案旁边的复选标记来完成此操作。它为您提供代表,回答者代表,并帮助下一个谷歌搜索者更快地找到合适的答案。

Instead of a string, you need to pass a function which directly references bar, so instead of this:

setInterval("bar("+n+")", 500);

Do this:

setInterval(function() { bar(n) }, 500);

You can see this working here

Also, you need to accept questions to get any future answers, you do this by clicking the checkmark beside the answer that helped you resolve the issue. It gives you rep, the answerer rep, and helps the next googler find the appropriate answer faster.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文