1

だから私はゼロまでカウントダウンし、ユーザーが続行できるようにdiv内のテキストを切り替えるjavascriptカウントダウンを作成しています。これが私のコードです:

<div id="top">
    You will be redirected in 10..
</div>

<script type="text/javascript">
    $(document).ready(function(){
        var timerId = 0;

            if(timerId == 0){
                timerId = window.setInterval(function() {
                    var timeCounter = 10;
                    var updateTime = parseInt(timeCounter,10) - 1;
                    $("#top").html("You will be redirected in " + updateTime + "...");

                    if(updateTime <= 0){
                        clearTimeout(timerId);
                        $("#top").html("Click to continue");
                    }
                }, 1000);
            }

     });
</script>

機能しますが、10 から 9 までしかカウントダウンしません。これはなぜですか?

4

5 に答える 5

2

Timecounter間隔内にあり、反復ごとに 10 に設定されます。カウントダウンするには、timecounter 変数を interval 関数の外に移動する必要があります。

<div id="top">
    You will be redirected in 10..
</div>

<script type="text/javascript">
    $(document).ready(function(){
        var timeCounter = 10,
            timerId = setInterval(function() {
               $("#top").html("You will be redirected in " + ( timeCounter-- ) + "...");
                if(timeCounter <= 0){
                    clearTimeout(timerId);
                    $("#top").html("Click to continue");
                }
            }, 1000);
     });
</script>

フィドル

于 2013-01-16T08:42:34.067 に答える
1

timeCount 変数をハードコーディングします。私の解決策:

HTML コード:

<div id="top">
    You will be redirected in <span id="timer">10<span>..
</div>

Javascript コード

$(document).ready(function(){
        window.setInterval(function() {
            var timeCounter = $('#timer').html();
            var updateTime = parseInt(timeCounter,10) - 1;
            $("#timer").html(updateTime);

            if(updateTime <= 0){                    
                $("#top").html("Click to continue");
            }
        }, 1000);


});

例: http://jsfiddle.net/ccAz6/1/

于 2013-01-16T08:49:05.037 に答える
1

デモ

var timerId = 0;

var timeCounter=10;

$(document).ready(function(){

            if(timerId == 0){
                timerId = window.setInterval(function() {

                    var updateTime = parseInt(timeCounter) - 1;
                    timeCounter--;

                   $("#top").html("You will be redirected in " + updateTime + "...");

                    if(updateTime <= 0){
                        clearTimeout(timerId);
                        $("#top").html("Click to continue");
                    }
                }, 1000);
            }

     });
于 2013-01-16T08:49:17.817 に答える
1

タイマーが経過するたびに、指定されたコールバックが実行されます。

コールバック (指定された関数の毎回の新しいインスタンス) 内では、timeCounter10 に設定します。

したがって、値は常に同じままです。

于 2013-01-16T08:43:52.073 に答える
1

時間カウンターを window.setInterval() 関数の外に出す必要があります。

ready 関数の内側にとどまることができますが、setInterval() メソッドの外側にはありません。

于 2013-01-16T08:45:12.167 に答える