jquery - 如果鼠标悬停一秒钟则执行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 调用。唯一的问题是无论用户是否将鼠标从文章上移开,它都会执行它。当用户将鼠标从文章上移开时,如果用户没有悬停至少一秒钟,我希望它取消。有什么建议么?
解决方案
将 setTimeout 函数分配给这样的变量
myVar = setTimeout(function(){ alert("Hello"); }, 3000);
在鼠标关闭事件上使用这个
clearTimeout(myVar);
推荐阅读
- python - 虚拟机上的 Neo4j 图形可视化可以嵌入到我的烧瓶 UI 中吗?
- python - 如何在无头模式下使用 selenium 抓取该站点?
- sql - SP执行时间极慢
- angular - 具有反应形式的角管道:仅适用于模糊
- image - SVG 无法在 IE / Edge 中正确显示
- windows - 如何从 Windows 命令提示符启动运行窗口(Windows 键 + R)?我还想定义 WHAT 程序 Run 应该在同一命令中打开
- c# - 动态加载 DropDownList
- c# - 通过 azure 函数以同步方式同时处理多个文件
- scheme - 方案中的嵌套条件和未指定的返回值
- python - np.uint8() 使法线向量计算错误