![](/img/trans.png)
[英]Javascript/Jquery Logic - Few Questions about Modal and .data
[英]jquery setTimeout few questions about it
我有一个带有标签系统的网站,就像在stackoverflow上工作的那种系统。 我对此的疑问是:
$("#area1 ul li").hover(function(){
var width= $(this).offset();
$(".flyout").css({"top":width.top+19,"left":width.left});
$(".flyout").toggle();
setTimeout(function() {
$.ajax({
url: web + "sources/queans/sql.php", type: "POST",
data: {
action: "taginfo",
tag: $(this).text(),
token: t,
ajax: "1"
},
success: function (output) {
$(".flyout").html(output);
}
});
}, 2000);
$(".flyout").html('<center><img style="margin-top:20px;" src="http://www.cloudynights.com/public/style_images/master/ajax_loading.gif" /> </center>');
});
鼠标悬停元素时,此Jquery脚本是否要等待2秒?
不完全是,一旦用户将鼠标悬停在元素上,就会启动计时器,并在2秒后执行操作。 用户不必为此而将鼠标悬停在元素上。
如果用户将鼠标悬停在该元素上,查询是否仍将运行并执行代码?
如上所述,该操作将在第一次将元素悬停2秒钟后执行,无论用户随后如何操作。
如果没有,如何在sql.php文件数据要求之前停止代码?
将对setTimeout
的调用结果捕获到一个变量(通常称为timerId
或类似名称)中,并在用户停止悬停元素时调用clearTimeout(timerId)
。
请参阅以下简化的演示。
var timerId; $('.container').hover(function(){ $('.message').text('Hover has been started, background will change in 5 seconds. Mouse out to cancel'); var $this = $(this); timerId = setTimeout(function(){ $this.css('background-color','red'); },5000); }, function(){ clearTimeout(timerId); $('.message').text('Action cancelled'); });
.container{ width:300px; height:300px; border: 1px solid black }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="container"> <div>Hover over me</div> <div class="message"></div> </div>
.hover()
通常.hover()
两个参数, handlerIn
和handlerOut
函数。 由于您只有一个函数,因此当mouse pointer enters the element
时将调用该函数。 我的理解是,您正在元素旁边显示一些弹出窗口,并在悬停时带有一些加载图标,这很好,因为向用户提供一些视觉反馈会鼓励他停留在该元素上。
setTimeout(callback,2000)
将在等待至少2秒后调用该回调(可以做更多-不能保证;)),但是如果用户离开该元素,则您仍会在不跟踪mouseleave
事件的情况下触发Ajax调用。 因此,将另一个函数传递给hover()
,该函数将在用户离开元素时被调用。
/* two variables outside hover scope to
hold reference to setTimeout & Ajax call*/
var timer, ajaxRequest;
$("#area1 ul li").hover(function(){
var width= $(this).offset();
$(".flyout").css({"top":width.top+19,"left":width.left});
$(".flyout").toggle();
timer = setTimeout(function() {
ajaxRequest = $.ajax({
url: web + "sources/queans/sql.php", type: "POST",
data: {
action: "taginfo",
tag: $(this).text(),
token: t,
ajax: "1"
},
success: function (output) {
$(".flyout").html(output);
}
});
}, 2000);
$(".flyout").html('<center><img style="margin-top:20px;" src="http://www.cloudynights.com/public/style_images/master/ajax_loading.gif" /> </center>');
},
function(){
// second callback to handle mouseleave
if(typeof ajaxRequest !== 'undefined'){
// abort the ongoing Ajax call
ajaxRequest.abort();
}else if(typeof timer !== 'undefined'){
// timeout callback is not invoked yet, so clear it
clearTimeout(timer);
}
// show some message in flyout or close the popup directly
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.