JQuery foreach计数

时间:2014-09-17 09:01:42

标签: javascript php jquery count

我有一段代码从我的数据库中获取结果,然后通过jQuery在我的页面上显示它:

var searchItem = function() {
    $('#search_results').css('top', '0px');
    $.getJSON('/json/searchitem/q/' + $('#json_search').val(), function(data){
        $('#search_results ul').fadeIn().html('');

        if($('#search_results table').css('display')=='none'){
            $('#search_results table').fadeIn();
        }

        $.each(data, function(i,item){
            $('#search_results').append('<tr><td>'+item.code+'</td></tr>');
        });
    });
};

现在,我想要的是我的结果是&gt; 10我希望在一个包含小行的表中显示它,5到10会产生正常的表结果,并且&lt; 2在大div。

有人能指出我如何做到这一点的正确方向吗? 我还没有JQuery的经验。

2 个答案:

答案 0 :(得分:3)

data是一个数组,data.length是数组中元素的数量。因此,您可以将其与不同的限制标准进行比较。

if (data.length > 10) {
    // Code to show table with small rows
} else if (data.length >= 5) {
    // Code for normal table
} else if (data.length < 2) {
    // Code for big divs
} else {
    // Not sure what you want for 2-4, but this is where it goes
}

答案 1 :(得分:2)

var searchItem = function() {
    $('#search_results').css('top', '0px');
    $.getJSON('/json/searchitem/q/' + $('#json_search').val(), function(data){
        $('#search_results ul').fadeIn().html('');

        if($('#search_results table').css('display')=='none'){
            $('#search_results table').fadeIn();
        }
       //Checks If result length is lessthan 2
        if(data.length < 2){
            // Show in big divs
        }else{
            //  show it in a table with small rows
             $.each(data, function(i,item){
               $('#search_results').append('<tr><td>'+item.code+'</td></tr>');
             });
        }
    });
};