[英]Clear a non-global timeout launched in jQuery plug-in
I try to set a timeout on an element, fired with a jQuery plugin. 我尝试在使用jQuery插件触发的元素上设置超时。 This timeout is set again in the function depending on conditions. 根据条件在功能中再次设置该超时时间。 But, I want to clear this element's timeout before set another (if I relaunch the plug-in), or clear this manually. 但是,我想在设置另一个元素之前清除该元素的超时(如果我重新启动该插件),或者手动清除它。
<div id="aaa" style="top: 0; width: 100px; height: 100px; background-color: #ff0000;"></div>
Here's my code (now on http://jsfiddle.net/Ppvf9/ ) 这是我的代码(现在在http://jsfiddle.net/Ppvf9/上 )
$(function() {
$('#aaa').myPlugin(0);
});
(function($) {
$.fn.myPlugin = function(loops) {
loops = loops === undefined ? 0 : loops;
this.each(function() {
var el = $(this),
loop = loops,
i = 0;
if (loops === false) {
clearTimeout(el.timer);
return;
}
var animate = function() {
var hPos = 0;
hPos = (i * 10) + 'px';
el.css('margin-top', hPos);
if (i < 25) {
i++;
} else {
if (loops === 0) {
i = 0;
} else {
loop--;
if (loop === 0) {
return;
} else {
i = 0;
}
}
}
el.timer = window.setTimeout(function () {
animate();
}, 1000/25);
};
clearTimeout(el.timer);
//$('<img/>').load(function() {
// there's more here but it's not very important
animate();
//});
});
return this;
};
})(jQuery);
If I make $('#element').myPlugin();
如果我做$('#element').myPlugin();
, it's launched. ,它已启动。 If I make it a second time, there's two timeout on it (see it by doing $('#aaa').myPlugin(0);
in console). 如果我第二次这样做,则有两个超时(通过在控制台中执行$('#aaa').myPlugin(0);
来$('#aaa').myPlugin(0);
)。 And I want to be able to clear this with $('#element').myPlugin(false);
我希望能够使用$('#element').myPlugin(false);
清除它$('#element').myPlugin(false);
. 。
What am I doing wrong? 我究竟做错了什么?
EDIT : SOLVED by setting two var to access this
and $(this)
here : http://jsfiddle.net/Ppvf9/2/ 编辑:通过设置两个变量来访问this
和$(this)
此处已解决: http : //jsfiddle.net/Ppvf9/2/
try saving the timeout handle as a property of the element. 请尝试将超时句柄保存为元素的属性。 Or maintain a static lookup table that maps elements to their timeout handles. 或维护将元素映射到其超时句柄的静态查找表。
Something like this: 像这样:
el.timer = window.setTimeout(...);
I assume you need one timer per element. 我假设您每个元素需要一个计时器。 Not a single timer for all elements. 不是所有元素都有一个计时器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.