[英]How to set constantly incrementing counter in javascript , to perform another operation when counter > certain value?
我是jquery和javascript的新手。 我需要在javascript中設置一個變量,該變量每秒鍾增加1。 為此,我做了以下工作:
function run(){
timer++;
}// run ends here
setInterval(run,1000);
一旦變量值> 5,我想啟用代碼,以便每當有人將鼠標懸停在html頁面中的iframe上時,就完成了ajax請求。
收到Ajax請求后,我想重置timer = 0。
if(timer>5){
$("iframe").hover(function(){
$.ajax({
url: 'http://localhost/test.html',
cache: false,
data: 'html',
success: function(data,status) {
}
});
});
timer=0;
}
該過程應再次重復,計數器應再次從0到5開始,並且應再次激活ajax請求功能。
下面是將完整的代碼放在一個位置:
<script>
var i = 0;
var timer=0;
function run(){
timer++;
}// run ends here
setInterval(run,1000);
if(timer>5){
$("iframe").hover(function(){
$.ajax({
url: 'http://localhost/test.html',
cache: false,
data: 'html',
success: function(data,status) {
}
});
});
timer=0;
}
</script>
我做了很多嘗試,並且用谷歌搜索了很多,但是無法找出解決方案。
嘗試這個 :
var timer=0;
function run(){
timer++;
if(timer == 5){
$("iframe").on('mouseenter', function(){
$.ajax({
url: 'http://localhost/test.html',
cache: false,
data: 'html',
success: function(data,status) {
timer=0;
$('iframe').off('mouseenter')
}
});
});
}
}// run ends here
setInterval(run,1000);
如果iframe上已經有mouseenter事件,則執行.off('mouseenter')
會刪除這些綁定。
正如伊恩(Ian)所建議的那樣,您可以為事件命名,從而可以取消綁定指定綁定。
為此,只需在綁定/取消綁定時使用一個點:
$("iframe").on('mouseenter.timer',...)
$('iframe').off('mouseenter.timer')
使用函數備注可避免全局“計時器”變量:
function run(){
run.timer = run.timer || 0;
return run.timer++;
} // run ends here
setInterval(run,1000);
為了相應地執行計時器操作,請從run()
運行處理,例如:
function run(){
run.timer = run.timer || 0;
run.timer = handleTimer(run.timer++);
} // run ends here
setInterval(run,1000);
function handleTimer(timer) {
if(timer > 5){
$("iframe").hover(function(){
$.ajax({
url: 'http://localhost/test.html',
cache: false,
data: 'html',
success: function(data,status) {
}
});
// And disable hover handler once executed
$("iframe").unbind("mouseenter mouseleave");
});
return 0;
}
return timer; // continue timer chaining
}
將您的if
語句放入run()
並將timer=0
移至AJAX調用的success
函數。
function run() {
timer ++;
if(timer == 5) {
//Your ajax here
}
}
您的AJAX success
應該看起來像success: function(data, status) { timer = 0;}
在您的AJAX成功中,您將要unbind
iframe
懸停,然后在timer > 5
時重新綁定它,以便在出現以下情況時刪除懸停功能計時器小於5。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.