简体   繁体   English

SetInterval 在多次调用 jQuery 插件时发生冲突

[英]SetInterval Collides When Calling a jQuery Plugin More than Once

I'm working on a custom jQuery plugin that makes use of SetInterval, but it breaks when it's called more than once.我正在开发一个使用 SetInterval 的自定义 jQuery 插件,但是当它被多次调用时它会中断。

I have something sort of like this:我有这样的东西:

(function($){
    $.fn.myplugin = function(options) {

        var defaults = {};
        var options = $.extend(defaults, options);
    var interval;

        this.each(function() {
            //etc.
            interval = setInterval(function(){ doMyOtherFunc(options); }, 1000);
        });

        function doMyOtherFunc(options) {
            //etc
        }

    }
})(jQuery);

Functionality works as expected if I call it once, but if I call it again on a second element it breaks.如果我调用它一次,功能会按预期工作,但如果我在第二个元素上再次调用它,它就会中断。

$('#myelement').myplugin({'option1', 'option2'});
$('#myotherelement').myplugin({'option1', 'option2'});

Somehow, the interval in the second instance overrides the one on the previous element, data and all.不知何故,第二个实例中的间隔覆盖了前一个元素、数据和所有的间隔。 (But the styling passed doesn't get screwed up.) Is this a weird limitation of setInterval, or am I doing something wrong? (但是通过的样式并没有搞砸。)这是 setInterval 的奇怪限制,还是我做错了什么?

You have to make the interval handle private to each element.您必须使每个元素的间隔句柄私有。 For this, you could use $.data :为此,您可以使用$.data

    this.each(function() {
        var interval = setInterval(function(){ doMyOtherFunc(options); }, 1000);
        $(this).data('myplugin-interval', interval);
    });

And you could retrieve the interval this way:您可以通过以下方式检索间隔:

$(this).data('myplugin-interval');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM