簡體   English   中英

如何在javascript中設置不斷遞增的計數器,當counter>確定值時執行另一操作?

[英]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。

JavaScript計數器,一定時數到3<div> 到達了</div><div id="text_translate"><p>我很難解決這個問題。 所以我得到了計數器,我想在用戶向下滾動頁面並達到某個 class 后從 0 慢慢計數到 3,在我的例子中是“.domov2”</p><p> 如果我刪除 API (EventListener),那么計數器工作得很好,但它已經在站點加載后立即開始計數。</p><p> 我設法做到了,但是當我向下滾動時不是執行 1 次,function 在到達 div 后執行了很多次滾動(我對 API 真的很糟糕)。 如何限制 function 執行 1 次並使其僅在條件下運行。</p><p> HTML:</p><pre class="lang-html prettyprint-override"> <section class="domov2"> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. </section> <div id="counter" data-target="3"> -1 </div></pre><p> JavaScript</p><pre> $(window).bind('scroll', function() { if($(window).scrollTop() >= $('.domov2').offset().top + $('.domov2').outerHeight() - window.innerHeight) { // create function startCount() const startCount = function() { // get number value from data-target and current number const target = +counter.getAttribute('data-target'); const count = +counter.innerText; // if count<target if (count < target) { // add to current value +1 var sestevek = count + 1 // replace current value in html with recently updated value "sestevek" counter.innerText = sestevek; // slow down condition for 0.3s setTimeout(startCount, 300); } else { //if current value is = target, then keep target counter.innerText = target; }}; //execute function startCount(); } });</pre></div>

[英]JavaScript counter, count to 3 when certain <div> is reached

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

相關問題 在 javascript 迭代器中遞增計數器 單擊按鈕時增加計數器(JavaScript,HTML) 計數器正在急劇增加(Javascript) Javascript計數器未正確遞增 自動增加JavaScript中的計數器 JavaScript對象作為計數器未遞增 防止Enter鍵不斷增加計數器 JavaScript旋轉遞增計數器從1開始 Javascript對象計數器未按預期增加 JavaScript計數器,一定時數到3<div> 到達了</div><div id="text_translate"><p>我很難解決這個問題。 所以我得到了計數器,我想在用戶向下滾動頁面並達到某個 class 后從 0 慢慢計數到 3,在我的例子中是“.domov2”</p><p> 如果我刪除 API (EventListener),那么計數器工作得很好,但它已經在站點加載后立即開始計數。</p><p> 我設法做到了,但是當我向下滾動時不是執行 1 次,function 在到達 div 后執行了很多次滾動(我對 API 真的很糟糕)。 如何限制 function 執行 1 次並使其僅在條件下運行。</p><p> HTML:</p><pre class="lang-html prettyprint-override"> <section class="domov2"> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. </section> <div id="counter" data-target="3"> -1 </div></pre><p> JavaScript</p><pre> $(window).bind('scroll', function() { if($(window).scrollTop() >= $('.domov2').offset().top + $('.domov2').outerHeight() - window.innerHeight) { // create function startCount() const startCount = function() { // get number value from data-target and current number const target = +counter.getAttribute('data-target'); const count = +counter.innerText; // if count<target if (count < target) { // add to current value +1 var sestevek = count + 1 // replace current value in html with recently updated value "sestevek" counter.innerText = sestevek; // slow down condition for 0.3s setTimeout(startCount, 300); } else { //if current value is = target, then keep target counter.innerText = target; }}; //execute function startCount(); } });</pre></div>
 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM