LoginSignup
0
3

More than 5 years have passed since last update.

カウントアップ・カウントダウン処理の実装とそのとき出くわしたJavascript比較処理の注意点

Last updated at Posted at 2017-04-26

カウントアップ・カウントダウン処理の実装を行いました。

以下のコードだと333→455にカウントアップします。値を入れ替えればカウントダウンします。

count-sample.html
<html lang="utf-8">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

<script> 

$(function(){
    var countElm = $('.count'),
    countSpeed = 7;

    countElm.each(function(){
        var self = $(this),
        countMax = Number(self.attr('data-num')),
        thisCount = Number(self.text()),
        countTimer;

        function upTimer(){
            countTimer = setInterval(function(){
                var countNext = thisCount++;
                self.text(countNext);

                if(countNext == countMax){
                    clearInterval(countTimer);
                }
            },countSpeed);
        }
        function downTimer(){
            countTimer = setInterval(function(){
                var countNext = thisCount--;
                self.text(countNext);

                if(countNext == countMax){
                    clearInterval(countTimer);
                }
            },countSpeed);
        }

        if(thisCount < countMax){
            upTimer();
        }else{
            downTimer();
        }
    });

});


</script>

<span class="count" data-num="450">333</span>

</html>

Javascript比較処理ではまった点

はじめは

countMax = self.attr('data-num'),
thisCount = self.text(),

としており、countMaxthisCountを文字列で比較していました。
javascriptの比較演算子は文字列で比較すると文字列のサイズで比較しているようで、上手く比較できていませんでした。

「比較演算子は数値型で比較するでしょっ」て思っていても、タグの要素を取ってきたりしているうちについついこんなことになってる場合があるという教訓でした。

0
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
3