jQuery 事件处理 .live() 与 setInterval 和clearInterval 的问题
jQuery 1.4.2:
我有一个图像。当触发鼠标悬停事件时,将执行一个函数,该函数运行一个循环来加载多个图像。相反,mouseout事件需要将图像设置回预定图像并且不再执行循环。这些仅适用于“thumb”类的图像:
$("img.thumb").live("mouseover mouseout", function(event) {
//var foo = $(this).attr('id');
var wait;
var i=0;
var image = document.getElementById(foo);
if (event.type == 'mouseover') {
function incrementimage()
{
i++;
image.src = 'http://example.com/images/file_'+i+'.jpg';
if(i==30) {i=0;}
}
wait = setInterval(incrementimage,500);
} else if (event.type == 'mouseout') {
clearInterval (wait);
image.src = 'http://example.com/images/default.jpg';
}
return false;
});
当我鼠标移开时,图像设置为default.jpg,但浏览器继续循环浏览图像。它永远不会停止。有人可以用一些知识来打我吗?谢谢。
jQuery 1.4.2:
I have an image. When the mouseover event is triggered, a function is executed that runs a loop to load several images. On the contrary, the mouseout event needs to set the image back to a predetermined image and no longer have the loop executing. These are only for the images with class "thumb":
$("img.thumb").live("mouseover mouseout", function(event) {
//var foo = $(this).attr('id');
var wait;
var i=0;
var image = document.getElementById(foo);
if (event.type == 'mouseover') {
function incrementimage()
{
i++;
image.src = 'http://example.com/images/file_'+i+'.jpg';
if(i==30) {i=0;}
}
wait = setInterval(incrementimage,500);
} else if (event.type == 'mouseout') {
clearInterval (wait);
image.src = 'http://example.com/images/default.jpg';
}
return false;
});
When I mouseout, the image is set to the default.jpg but the browser continues to loop though the images. It will never stop. Can someone hit me with some knowledge? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以将代码缩短至此以正确清除间隔:
这会拆分
.live()< /code>
调用使逻辑更清晰一些,并使用
.data()
而不是作为全局变量。You can shorten your code down to this to clear the interval properly:
This splits the
.live()
calls to make the logic a bit cleaner, and stores the previouswait
id on the element itself using.data()
instead of as a global variable.问题是 mouseout 事件没有看到与 mouseover 事件相同的
wait
。您需要将其存储在其他地方。我建议使用 [data()][1]
将其存储在元素上。此外,这个序列没有意义:
this
已经是图像元素。最后,这不是我定义该函数的方式。尝试类似的方法:
The problem is that the mouseout event doesn't see the same
wait
that the mouseover event did. You need to store it somewhere else. I would suggest using [data()][1]
to store it on the element.Also, this sequence doesn't make sense:
this
is already the image element.Lastly, that's not how I'd define the function. Try something like:
您是否尝试过将
var wait
移到 .live() 事件之外?Have you tried moving your
var wait
outside your .live() event?