如何实现Javascript语法对齐(moment.js)?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (84)

在使用时间戳,moment.js和finddrama提供的实现示例时,将以下内容添加到html站点:

<span id="then" data-date="Aug 22 2018 11:33:00 GMT-0700 (PDT)"></span>

<script>
      $(document).ready(function(){
        var then = $('#then'),
            date = moment(new Date(then.attr('data-date'))),
            update = function(){
                       then.html(date.fromNow());
                     };

        update();
        setInterval(update, 60000);
      });

      </script>

输出结果成功

<span id="then" data-date="Aug 18 2018 07:33:00 GMT-0700 (PDT)"></span>

<span id="then1" data-date1="Aug 3 2018 16:33:00 GMT-0700 (PDT)"></span>

<script>
      $(document).ready(function(){
        var then = $('#then'),
            date = moment(new Date(then.attr('data-date'))),
            update = function(){
                       then.html(date.fromNow());
                     };

        update();
        setInterval(update, 60000);
      });

      </script>

<script>
      $(document).ready(function(){
        var then = $('#then1'),
            date = moment(new Date(then.attr('data-date1'))),
            update = function(){
                       then.html(date.fromNow());
                     };

        update();
        setInterval(update, 60000);
      });

      </script>
提问于
用户回答回答于

首先提供跨元素的类名,然后解析到每个span元素,,使数据属性通用,即数据日期,而不是每个跨度的不同,然后解析整个span并追加html

<span class="then" data-date="Aug 18 2018 07:33:00 GMT-0700 (PDT)"></span>

<span class="then" data-date="Aug 3 2018 16:33:00 GMT-0700 (PDT)"></span>

<script>
  $(document).ready(function(){
    $('.then').each(function(i) {
      var $this = $(this);
      var date = moment(new Date($this.attr('data-date')));
      var update = function() {
         $this.html(date.fronNow());
      };
      update();
      setInterval(update, 60000);
    });

   });
  </script>
用户回答回答于

这将找到类中的所有DOM元素,然后查找它们的每个数据日期属性,并将它们的内部HTML设置为tag.js对象

<span class="then" data-date="Aug 22 2018 11:33:00 GMT-0700 (PDT)"></span>
<span class="then" data-date="July 15 2018 9:33:00 GMT-0700 (PDT)"></span>

<script>
$(document).ready(function(){
  var dates = $('.then');
  $.each(dates, function(){
    var date = moment(new Date($(this).attr('data-date')))
    $(this).html(date.fromNow());
  })
});
</script>

扫码关注云+社区

领取腾讯云代金券