繁体   English   中英

JavaScript使用HTML表单过滤JSON对象

[英]JavaScript filter JSON objects using HTML forms

单击HTML复选框时,我希望过滤JSON数组中的对象列表。 我知道JavaScript的array.sort()方法,但是如何根据复选框的点击次数消除项目? 我需要一个事件监听器吗?

我的JSON看起来像这样:

{ "lots" : [
    {
    "name" : "Parking Lot Name",
    "price" : 2,
    "cash" : true,
    "credit" : false,
    "address" : "1234 W Main Ave",
    "center" : {
        "lat" : 67.659414,
        "lng" : -137.414730
    }... etc.

因此,如果我有一个包含用于根据付款类型消除停车场的复选框的表格,我应该如何实施呢? 我已经读过有关jQuery array.grep()函数的信息,对吗?

我的页面是使用JS循环构建的,如下所示:

makeList(){
var self = this;

self.jsonFile = $.ajax({
 type: 'GET',
 url: 'assets/data/default.json',
 dataType: 'json',
 success: function(response) {
   console.log(response);
 }
});

self.jsonFile.done(function(data){
  //Sort low to high by default
  data.lots.sort(function(a, b){
    return(a.price > b.price)
  });

  for (var i = 0; i < data.lots.length; i++) {
    document.getElementById('jsonList').innerHTML +=
      '<li>
        <div id="text">
          <p class="price"> 
            $' + data.lots[i].price +  '.00
          </p>
          <p class="info">' +
            data.lots[i].address +
         '</p>
        </div>
        <form method="get">
          <button type="submit" formaction="https://www.google.com/maps/dir/Current+Location/' +
           data.lots[i].address +
           '">Directions
          </button>
          <button type="submit" formaction="detail-view.html">Details
          </button>
        </form>
      </li>';
  }
});

}

您可以像这样消除:您必须将onchange函数绑定到复选框,然后对函数使用以下方法

  data = [{
      "name": "name",
      "location1": "no",
      "description": "description of services"
      },
     {
      "name": "name2",
      "location1": "yes",

      "description": "description of services2"
       },
       {
        "name": "name3",
         "location1": "no",

        "description": "description of services3"
    }
  ];

   b = $.grep(data, function(el, i) {
     return el.location1.toLowerCase() === "yes" 
   });

您可以使用以下方式获得付款类型为“现金”的批次:

var cashLots = data.lots.filter(function(lot){return lot.cash});

作为箭头功能:

var cashLots = data.lots.filter(lot => lot.cash);

暂无
暂无

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

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