如何使用json和jquery进行排序

How to sorting with json & jquery?

本文关键字:排序 jquery 何使用 json      更新时间:2023-09-26

>我使用ajax creat html,像这样

html += "<div class='"cloumns rentprice'">" + data[i].car_price + "</div>";

我想捕获 json 的值用于索引表单这个动态 html,

然后排序,

我的排序代码是这样的

$("#rentPrice").click(function(){
        var $this=$(this);
        $("#rentPrice").not($this)
            if ($this.hasClass("up")){
                $this.removeClass().addClass("down");
            }else{
                $this.removeClass().addClass("up");
            }
            var index = $(".rentprice").text();
            var direction =$this.attr("class");
            sort(index,direction);
            show(json);
    });

    function sort(index, direction){
        json.sort(function(a,b){
            var keys = Object.keys(a);
            if (direction == "up"){
                if (a[keys[index]] > b[keys[index]]){
                    return 1;
                }else if (a[keys[index]] < b[keys[index]]){
                    return -1;
                }else{
                    return 0;
                }
            }else{
                if (a[keys[index]] < b[keys[index]]){
                    return 1;
                }else if (a[keys[index]] > b[keys[index]]){
                    return -1;
                }else{
                    return 0;
                }
            }
        });
    }
});

但答案是错误的,因为var index = $(".rentprice").text();无法获得索引data[i].car_price

我不知道怎么get data[i].car_price表单html,怎么办?知道吗?

此代码获取带有 "rentprice" 类的第一项 ( eq(0) ):

$(".rentprice").eq(0).text()

此代码对每个项目执行一些操作:

$.each($(".rentprice"), function(){
    alert($(this).text());
});

我建议您使用库来处理像 knockoutjs.com 这样的数据可视化。它为数据排序和编辑提供了更好、更稳定的解决方案