【问题标题】:Interval doesn't stop on mouseout鼠标悬停时间隔不会停止
【发布时间】:2016-06-20 01:19:21
【问题描述】:

如果我将鼠标移出之前触发间隔功能的元素,则间隔“myInterval”不会停止。为什么不停止?

$(".postimagepic").mouseenter(function () {
    var link = $("#blurpost").attr("src").split("/").pop().split(".", 1)[0];
    var myInterval = setInterval(function () {
        $.ajax({
            url: 'asdf.php',
            type: 'post',
            data: {
                'user': 'yy',
                'topost': link
            },
            success: function () {

            }
        });
    }, 1000);
}).mouseout(function () {
    clearInterval(myInterval);
});

【问题讨论】:

  • myIntervalmouseenter 回调函数的私有。在事件绑定代码上方声明变量。 代码: var myInterval; .... $(".postimagepic").mouseenter(function() { myInterval = setInterval....。另外,请使用hover
  • Moritz,Web 开发中的两个关键工具是浏览器的 Web 控制台(如果您查看,它会向您显示错误)及其内置调试器。使用 F12 或 Ctrl+Shift+I 或 Cmd+Shift+I 打开浏览器的开发工具。

标签: jquery intervals mouseleave mouseout


【解决方案1】:

变量myIntervalmouseenter 回调函数的私有,因此在该函数之外无法访问。要使其可从mouseout 回调函数访问,请在函数外部声明该变量。

var myInterval; // Define it here to make it global

$(".postimagepic").mouseenter(function () {
    var link = $("#blurpost").attr("src").split("/").pop().split(".", 1)[0];
    myInterval = setInterval(function () {
        $.ajax({
            ...
        });
    }, 1000);
}).mouseout(function () {
    // Accessible here
    clearInterval(myInterval);
});

我还建议使用hover() 而不是mouseentermouseout 事件。

var myInterval; // Define it here to make it global

$(".postimagepic").hover(function () {
    var link = $("#blurpost").attr("src").split("/").pop().split(".", 1)[0];
    myInterval = setInterval(function () {
        $.ajax({
            ...
        });
    }, 1000);
}, function () {
    clearInterval(myInterval);
});

【讨论】:

  • 试过了,但我的声望仍然低于 15... :)
【解决方案2】:

为了使全局变量,声明变量名不带var关键字。

如下

$(".postimagepic").mouseenter(function () {
        var link = $("#blurpost").attr("src").split("/").pop().split(".", 1)[0];
        myInterval = setInterval(function () { //change here only
            $.ajax({
                url: 'asdf.php',
                type: 'post',
                data: {
                    'user': 'yy',
                    'topost': link
                },
                success: function () {

                }
            });
        }, 1000);
    }).mouseout(function () {
        clearInterval(myInterval);
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-27
    • 2012-05-04
    • 2012-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-27
    • 2014-09-22
    相关资源
    最近更新 更多