![](/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.