繁体   English   中英

如何使用jquery根据if条件获取总数

[英]how to get the total number count based on if condition using jquery

在这里我正在使用AJAX,它工作正常,在成功功能中,我正在获得所有状态值,例如Active,ACTIVE_DRAFT,Pending。像这样计数多少活跃状态,所以我正在尝试这样,但我无法获得计数,我得到console.log(count); id的字符串长度。

 $.ajax({ url: 'http://example.com/api/get/mylisting', type: 'GET', contentType: 'application/json; charset=utf-8', success: function(active_draft_sell, textStatus, xhr) { var count = 0 ; $.each(active_draft_sell, function(key, value) { var status = value.status; var listingtype = value.listingtype; if (status == "ACTIVE")) { var id = value.id; console.log(value.id); var count = id.length; count++; console.log(count); } }); } }); 

尝试这个:

$.ajax({
    url: 'http://example.com/api/get/mylisting',  
    type: 'GET',
    contentType: 'application/json; charset=utf-8',
    success: function(active_draft_sell,textStatus, xhr) {

        var count = 0;
        $.each( active_draft_sell, function( key, value ) {
            var status = value.status;
            var listingtype = value.listingtype;
            if(status == "ACTIVE"){ 
                count++;
                console.log(count);
            }
        });
    }
});

如果返回多个值,则需要更新$.each函数之外的变量,以便跟踪所有处于“ Active状态的项目。

$.ajax({
  url: 'http://example.com/api/get/mylisting',  
  type: 'GET',
  contentType: 'application/json; charset=utf-8',
  success: function(active_draft_sell,textStatus, xhr) {
    var count = 0;
    $.each( active_draft_sell, function( key, value ) {
        var status = value.status;
        var listingtype = value.listingtype;

        if(status == "ACTIVE") {   
            count++;                
        }
    });
    console.log(count);
  }
});

尝试这个。 您将在循环内获得计数。

$.ajax({
  url: 'http://example.com/api/get/mylisting',
  type: 'GET',
  contentType: 'application/json; charset=utf-8',
  success: function(active_draft_sell, textStatus, xhr) {

    var count = 0 ;
    for(var i = 0; i < active_draft_sell.length; i++) {
       if(active_draft_sell[i].status == "ACTIVE"){
          count++;
       }
    } 

    $.each(active_draft_sell, function(key, value) {
        var status = value.status;
        var listingtype = value.listingtype;

        console.log(count);
      }
    });
  }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM