首页 > 解决方案 > 如果鼠标悬停一秒钟则执行ajax函数,如果鼠标悬停则取消

问题描述

我目前有从 mySQL 数据库加载的用户文章,其中包括文章的标题和用户为文章提交的封面图片。当用户将鼠标悬停在文章上一秒钟时,我希望显示文章的“预览”,其中包括文章的一些文本、文章的主题、字数以及在文章。只有当用户将鼠标悬停在文章上一秒钟(为简单起见缩短)时,我才想出一个执行此 ajax 请求的函数:

    $(".articles").on("mouseenter", ".article-container-divs", function() {

        setTimeout(function() {

                $.ajax({
                    url: 'includes/articles/getArticlePreview.php',
                    type: 'POST',
                    data: {articleId: articleId, idUsers: idUsers},
                    dataType: 'json',
                    success: function(data) {
                        data.forEach(function(item) {

                            var wordCount = item.article.split(' ').length;
                            var topic = item.topic.slice(0,1).toUpperCase() + item.topic.slice(1).toLowerCase();

                            thisElement.find(".previewTopic").html("<span class='previewStyle'>Topic:</span> " + topic);
                            thisElement.find(".previewWordCount").html("<span class='previewStyle'>Word Count:</span> " + wordCount);
                            thisElement.find(".previewLikes").html("<span class='previewStyle'>Likes:</span> " + item.voteCount);
                            thisElement.find(".previewArticle p").html(item.article);

                        });
                    }
                });

        }, 1000);

    });

我尝试包含一个setTimeout()函数,该函数在一秒钟后执行 AJAX 调用。唯一的问题是无论用户是否将鼠标从文章上移开,它都会执行它。当用户将鼠标从文章上移开时,如果用户没有悬停至少一秒钟,我希望它取消。有什么建议么?

标签: jquery

解决方案


将 setTimeout 函数分配给这样的变量

myVar = setTimeout(function(){ alert("Hello"); }, 3000);

在鼠标关闭事件上使用这个

clearTimeout(myVar);

推荐阅读