简体   繁体   English

对从 JSon 数组填充的 JQuery 列表进行排序

[英]Sorting a JQuery list, populated from a JSon array

I tried many different methods but can't seem to work this one out.我尝试了许多不同的方法,但似乎无法解决这个问题。 I have a JSon array which populates my JQuery list.我有一个 JSon 数组,它填充了我的 JQuery 列表。 The list displays correctly, but I cant seem to be able to filter it.该列表显示正确,但我似乎无法过滤它。

I'd like to be able to filter by name or price.我希望能够按名称或价格进行过滤。 I tried the JQuery.Filter method and many others, and they all failed.我尝试了 JQuery.Filter 方法和许多其他方法,但都失败了。 I'd also like to make it as a link.我也想把它作为一个链接。 ( The user clicks sort by name, and it sorts... ) (用户单击按名称排序,它排序...)

Heres what I have so far, which I was convinced would work.这是我到目前为止所拥有的,我确信它会起作用。

Any help is greatly appreciated, Thanks !非常感谢任何帮助,谢谢!

.js file: .js 文件:

// Json array var productList = {"products": [ {"description": "Product 1", "price": "3.25"}, {"description": "Product 4", "price": "9.97"}, {"description": "Product 3", "price": "4.21"}, {"description": "Product 2", "price": "5.24"}, {"description": "Product 5", "price": "8.52"} ] };

function loadList() {

var list = $("#productList").listview();

// load array into list

$(productList.products).each(function(index) {
    $(list).append('<li id="listitem">' + this.description + "  " +
            "    :     " + this.price + '</li>');

     // sort by price 
     $(productList.products).filter(function ()
     { return parseFloat(this.price) < 11;})

});

$(list).listview("refresh"); }

How about this for sorting :这个排序怎么样:

var prods = productList.products.sort(function(a, b) {return parseInt(a.price) < parseInt(b.price);});
$.each(prods, function() {
    list.append("<li>" + this.description + " : " + this.price + "</li>");
});

To sort by description, you could use this instead:要按描述排序,您可以改用它:

var prods = productList.products.sort(function(a, b) {return a.description < b.description;});

If you just want to filter , you could substitute:如果你只想过滤,你可以替换:

var prods = productList.products.filter(function(item) {return parseInt(item.price) < 5;});

This sort of filtering is typically best done on the server-side end of things.这种过滤通常最好在服务器端完成。 Have you tried applying the filtering at the DB or application-levels?您是否尝试过在数据库或应用程序级别应用过滤?

There have been a lot of json path (xpath like) tools popping up for this kind of purpose.出于这种目的,出现了很多 json 路径(类似 xpath)工具。 Check out http://goessner.net/articles/JsonPath/查看http://goessner.net/articles/JsonPath/

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

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