jQuery多个倒计时的实现

时间:2022-10-25 22:04:43

1.jquery代码

<script type="text/javascript">
   var jsq = {
      startdata: [],
      enddata: [],
      addStart: function (key, value) {
         if (typeof(jsq.startdata[key]) == 'undefined') {
            jsq.startdata[key] = value;
         }
      },
      addEnd: function (key, value) {
         if (typeof(jsq.enddata[key]) == 'undefined') {
            jsq.enddata[key] = value;
         }
      },
      addAll: function () {
         $(".remain-time").each(function (i) {
            var key = $(this).data("id");
            var startValue = $(this).attr("starttime");
            var endValue = $(this).attr("endtime");

            if (startValue >= endValue) {
               if (typeof(jsq.startdata[key]) == 'undefined') {
                  jsq.addStart(key, startValue);
                  jsq.addEnd(key, endValue);
               }

            } else {
               //超过倒计时,状态变为重新选派
               ajaxPost('/order/ajax_auto_change', {oid: key}, function () {
                  $("#order_time_" + key).parent().parent().parent().parent().remove();//删除
               }, function () {
                  remind(key + '号订单,派送员接单过期,自动更换状态出错');
               });
            }

         });

         jsq.subAll();
      },
      subAll: function () {
         for (var index in jsq.startdata) {
            var remainTime = (jsq.startdata[index] - jsq.enddata[index]);

            if (remainTime >= 0) {
               jsq.startdata[index]--;

               var second = Math.floor(remainTime % 60);
               var minite = Math.floor((remainTime / 60) % 60);

               $('#order_time_' + index).text(minite + "分" + second + "秒");
            } else {
               location.reload();
            }
         }
      }

   };

   $(function () {
      //倒计时
      setInterval('jsq.addAll()', 1000);

   });

</script>

2.html页面

<div>
    <h5 class="text-success">倒计时 :</h5>

    <p id="order_time_<?= $item->id; ?>" data-id="<?= $item->id; ?>"
       endtime="<?= time(); ?>"
       starttime="<?= $item->updated + (60 * 5); ?>"
       class="text-success remain-time">
    </p>
</div>