使用Jquery在名称和成本之间对Json数据进行排序吗?

时间:2019-05-20 12:01:49

标签: javascript jquery json sorting

嗨,我有此功能,可以检索产品名称和成本并将其输入到我的html中。我希望能够通过单击“产品”标题或“成本”标题在名称和成本之间进行排序。我已经弄清楚了如何按名称对我的产品进行排序,但这就是没有单击功能的函数。 这就是到目前为止,我的代码只按字母顺序对数据进行排序

function drawPage() {
    $.get('/products', function (data) {
        console.log(data);
        var prod = data.products;
        prod.sort(function(a, b){
              var x = a.name.toLowerCase();
              var y = b.name.toLowerCase();
              if (x < y) {return -1;}
              if (x > y) {return 1;}
              return 0;
        });
        for(var i=0; i<prod.length; i++){
        var el = document.createElement('P');
        el.innerHTML = prod[i].name;
        var al = document.createElement('P');
        al.innerHTML = prod[i].unit_cost;
            $('#app').append(el);
            $('#costof').append(al);
        }
    })
}
document.addEventListener('load', drawPage());


    <div class="row">
        <div class="column">
            <div id="app"> Product
            </div>
        </div>
        <div class="column">
            <div id="costof"> Cost
            </div>
        </div>
    </div>

我的Jquery代码高于我的HTML代码

我希望能够在按成本排序和按产品名称排序之间切换,但我无法弄清楚。

谢谢

1 个答案:

答案 0 :(得分:0)

请查看此示例

HTML和jQuery

let products = [{name: "Colgate", cost: 50},
                {name: "Anchor", cost: 45},
                {name: "Pepsodent", cost: 55},
                {name: "Miswak", cost: 60},
                {name: "CloseUp", cost: 20},
                {name: "DantKanti", cost: 70},
                {name: "Dabur", cost: 30},
                {name: "Lal DantManjan", cost: 58},
                {name: "MaxFresh", cost: 55},
                {name: "Salty", cost: 89}];

function printList(sortingProp){
  
  $("#products").html("");
  
  if(sortingProp==="name")
    products.sort((a, b) => {
    let nameA = a.name.toUpperCase(); // ignore upper and lowercase
    let nameB = b.name.toUpperCase(); // ignore upper and lowercase
    if (nameA < nameB) {
      return -1;
    }
    if (nameA > nameB) {
      return 1;
    }

    // names must be equal
    return 0;
    });
  else
    products.sort((a,b)=> a.cost-b.cost );
    

  products.forEach((el)=>{
    let htmlEl = document.createElement('li');
    
    htmlEl.innerHTML = "<span><b>"+el.name+"</b></span>"+
                      "<span style='float:right'><b>"+el.cost+"</b></span>"
  
    $("#products").append(htmlEl);
  });
  
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
  
  <button onclick="printList('name')">Sort By Name</button>
  
  <button onclick="printList('cost')">Sort By Cost</button>
  
  <ul id="products"></ul>
</body>
</html>