代码之家  ›  专栏  ›  技术社区  ›  da_root

动画JSON值的计数并替换null

  •  1
  • da_root  · 技术社区  · 7 年前

    是否可以实现json数据的动画计数js。我试过了,但还是回来了。这是我的代码:

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <div id="number"><span class="count">Count</span></div>
    <div id="id">Id: </div>
    <div id="pos">POS: </div>
    
    <div> Static Number</div>
    <div class="count">345678912</div>
    <script type="text/javascript">
        $('.count').each(function () {
        $(this).prop('Counter',0).animate({
            Counter: $(this).text()
        }, {
            duration: 4000,
            easing: 'swing',
            step: function (now) {
                $(this).text(Math.ceil(now));
            }
        });
    });
        </script>
    

    JS公司:

    var info = {"city":[
    {"id":"4","number":"376478","pos":"null"},
    {"id":"5","number":"4565878","pos":"3"},]};
    
    var res = info.city.filter(function(item){
      return item.id=='4';
      function CheckNullReturnBlank(item) {
        return item = (item == null) ? 'No Data' : item;
    }
    });
    console.log(res);
    var HTML = '<span>'+res[0].number+'</span>';
    $('.count').append(HTML);
    var HTML ='<span>'+res[0].id+'</span>';
    $('#id').append(HTML);
    var HTML ='<span>'+res[0].pos+'</span>';
    $('#pos').append(HTML);
    

    但如果我使用静态数字进行测试,动画效果会非常好。另一件事是,我试图将json中的空值替换为无可用数据,但没有运气。感谢您对我的帮助。

    这是JSFIDLE链接: http://jsfiddle.net/zeef/vLw5wo5p/3/

    1 回复  |  直到 7 年前
        1
  •  1
  •   Julius Dzidzevičius    7 年前

    存在一些问题:

    • 你写的 item == null ,而“null”是字符串。
    • 您的项是一个对象,您需要的是它的属性( item.pos == 'null' )
    • 你得到 NaN 因为在你的第一次 .count span您有“Count”字符串,即。。不是数字:)
    • 您的筛选函数永远不会到达 CheckNullReturnBlank 作用
    • 并且您将动画脚本放在HTML中,这样它会在其他Javascript之前加载,所以动态添加的内容不会受到HTML中脚本的影响。

    var info = {"city":[
    {"id":"4","number":"376478","pos":"null"},
    {"id":"5","number":"4565878","pos":"3"},]};
    
    var res = info.city.filter(function(item){
      return item.id=='4';
    });
    
    res.forEach(function(item) {
    	item.pos = (item.pos == 'null') ? 'No Data' : item.pos;
    });
    
    console.log(res);
    var HTML = '<span>'+res[0].number+'</span>';
    $('.count').append(HTML);
    var HTML ='<span>'+res[0].id+'</span>';
    $('#id').append(HTML);
    var HTML ='<span>'+res[0].pos+'</span>';
    $('#pos').append(HTML);
    
    $('.count').each(function () {
      $(this).prop('Counter',0).animate({
          Counter: $(this).text()
      }, {
          duration: 4000,
          easing: 'swing',
          step: function (now) {
              $(this).text(Math.ceil(now));
          }
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <div id="number">Count <span class="count"></span></div>
    <div id="id">Id: </div>
    <div id="pos">POS: </div>
    
    <div> Static Number</div>
    <div class="count">345678912</div>