2011-09-29 26 views
0

我有一個從0到指定的數字計數並在計數時顯示它的代碼。 問題是我想在使用jQuery mobile製作的web應用程序中使用代碼。 當代碼與普通的HTML一起使用時,我工作的很好,但是當我使用它與jQuery移動時,它不會工作。 我不希望數字開始計算,直到某個移動頁面加載,有沒有辦法做到這一點? 我認爲這個問題是因爲在jquery mobile中,所有的頁面都包含在一個html文檔中,並且當html頁面打開時我需要計數數字,我希望它在顯示'#about'部分時開始計數?jQuery數字計數器與jQuery的移動

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html> 
<head> 
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> 
    <script type="text/javascript"> 
$(function() { 
    $('#foo').counter({ 
     start: 1000, 
     end: 400000, 
     time: 1, 
     step: 50, 
     callback: function() { 
      $("#foo").html("400000"); 
     } 
    }); 
}); 

;(function($) {   
    $.fn.counter = function(options) { 


     var options = $.extend(defaults, options); 

     var counterFunc = function(el, increment, end, step) { 
      var value = parseInt(el.html(), 10) + increment; 
      if(value >= end) { 
       el.html(Math.round(end)); 
       options.callback(); 
      } else { 
       el.html(Math.round(value)); 
       setTimeout(counterFunc, step, el, increment, end, step); 
      } 
     } 

     $(this).html(Math.round(options.start)); 
     var increment = (options.end - options.start)/((1000/options.step) * options.time); 

     (function(e, i, o, s) { 
      setTimeout(counterFunc, s, e, i, o, s); 
     })($(this), increment, options.end, options.step); 
    } 
})(jQuery); 
    </script> 
    <style type="text/css"> 
    </style> 
</head> 

<body> 
    <span id="foo"></span> 
</body> 
</html> 

回答

1

查看jQuery Mobile的事件文檔:http://jquerymobile.com/demos/1.0rc1/docs/api/events.html

您不想在document.ready上運行您的代碼,而是想在pageshow上運行它。

變化:

$(function() { 
    $('#foo').counter({ 
     start: 1000, 
     end: 400000, 
     time: 1, 
     step: 50, 
     callback: function() { 
      $("#foo").html("400000"); 
     } 
    }); 
}); 

要:

$(document).delegate('#about', 'pageshow', function() { 
    $('#foo').counter({ 
     start: 1000, 
     end: 400000, 
     time: 1, 
     step: 50, 
     callback: function() { 
      $("#foo").html("400000"); 
     } 
    }); 
}); 

我沒有用在「反向」插件,所以我不知道怎麼做,但你可能要停止計數器時用戶導航到另一個頁面,只需將代碼停止計數器與pagehide事件綁定:

$(document).delegate('#about', 'pagehide', function() { 
    //code to stop counter goes here 
}); 

A注:我使用.delegate()功能上$(document)對象行爲像.live()功能使用時在其上方的例子:

$(document).delegate('#about', 'event-name', function() {});類似於$(#about).live('event-name', function() {});然而.delegate()執行更有效。代表的文檔在這裏:http://api.jquery.com/delegate/

+0

感謝您的幫助,好吧,我認爲這將工作,但是,當我導航到佇列中的頁面時,計數器將顯示一瞬間然後消失。你有什麼想法爲什麼這樣做? – mcneela86