【问题标题】:How to sorting with json & jquery?如何使用 json 和 jquery 进行排序?
【发布时间】:2015-03-14 19:02:10
【问题描述】:

我用ajax creat html,像这样

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

我想从这个动态 html 中获取用于索引的 json 值,

然后排序,

我的排序代码是这样的

$("#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 form html ,我该怎么办?有什么想法吗?

【问题讨论】:

标签: javascript jquery json sorting dynamic


【解决方案1】:

此代码获取具有“rentprice”类的第一项 (eq(0)):

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

这段代码对每个项目做一些事情:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-11
    • 1970-01-01
    • 1970-01-01
    • 2014-09-27
    • 2012-01-16
    相关资源
    最近更新 更多