繁体   English   中英

在纯JS上通过三种不同的过滤器从JSON文件中过滤产品?

[英]Filtering products from a JSON file by three different filters on pure JS?

我是JS的新手,所以我想向经验丰富的程序员寻求帮助。
我目前拥有的内容:1)我在HTML中写了-过滤器:
a)列表过滤器
b)通过复选框过滤
c)使用滑块和输入按价格过滤

2)有一个json文件,其中存储了四个商品(对象)
3)有一个JS文件在页面上显示这些产品

这是现在的样子: http : //i.piccy.info/i9/d00c8e6e5d116f383e6488267eb0761d/1566815950/104418/1334636/Screenshot_4.jpg

我需要在开始时显示所有产品,当我检查,输入价格或从列表中选择类别时,仅显示选定的产品。
我知道互联网上到处都是现成的jquery解决方案,但是在我的小项目中应该有纯js。

这是什么的代码:
HTML:

<div id = "filters">
     <div class = "country"> <h2> Country </h2>
       <select id = "country">
       <option value = "hide"> - Country - </option>
       <option value = "turkey"> Turkey </option>
       <option value = "china"> China </option>
       <option value = "france"> France </option>
       <option value = "italy"> Italy </option>
       </select>
     </div>
    
      <div class = "size"> <h2> Size </h2>
      <div id = "myDropdown">
        <input type = "checkbox" class = "btn" value = "S"> S <br>
        <input type = "checkbox" class = "btn" value = "M"> M <br>
        <input type = "checkbox" class = "btn" value = "L"> L <br>
        <input type = "checkbox" class = "btn" value = "XL"> XL <br>
      </div>
      </div>
      
     <div class = "price"> <h2> Price </h2>
       <div class = "price-input"> <input class = "input-text" type = "text" value = ""> & nbsp; - & nbsp; </div>
       <div class = "price-input"> <input class = "input-text" type = "text" value = ""> & nbsp; usd & nbsp; </div>
       <button id = "submitprice" type = "submit"> OK </button>
          <input type = "range" min = "1" max = "100" value = "50">
    </div>
</div>
           
<div id = "goods"> </div>

<script> var sex = 'male' </script>

JS:

document.addEventListener ('DOMContentLoaded', function (e) {
  loadGoods ();
});

function loadGoods () {
    $ .getJSON ('goods.json', function (data) {
        var out = '';
        for (var key in data) {
            if (data [key] ['sex']! = sex) {continue; }
            out + = '<div class = "single-goods">';
            out + = '<h3>' + data [key] ['name'] + '</h3>';
            out + = '<img src = "' + data [key] .image + '">';
            out + = '<p> Price:' + data [key] ['cost'] + '</p>';
            out + = '<button class = "add-to-cart" data-art = "' + key + '"> Buy </button>';
            out + = '</div>';
        }
         document.getElementById ('goods'). innerHTML = out;
    });
}

JSON:

{
  "Shirt number 1": {
      "sex": "male",
    "name": "Shirt No. 1",
    "cost": 1000,
    "country": "argentina",
    "image": "http://i.piccy.info/i9/9921ed03bf45751d45447b15e78be751/1566814909/19890/1334636/1.jpg",
    "size": "S"
  },
  "Shirt number 2": {
      "sex": "male",
    "name": "Shirt No. 2",
    "cost": 1200,
    "country": "argentina",
    "image": "http://i.piccy.info/i9/acc4df9b14e48a42d7cd353e923673e7/1566814962/22015/1334636/2.jpg",
    "size": "M"
  },
  "Shirt number 3": {
      "sex": "male",
    "name": "Shirt number 3",
    "cost": 1700,
    "country": "argentina",
    "image": "http://i.piccy.info/i9/174610be67bfea39f99c956885ae3786/1566815027/25896/1334636/3.jpg",
    "size": "L"
  },
"Shirt number 4": {
    "sex": "male",
    "name": "Shirt No. 4",
    "cost": 2000,
    "country": "argentina",
    "image": "http://i.piccy.info/i9/e2e5c6cb274121b9898b7d45a085130f/1566815049/29582/1334636/4.jpg",
     "size": "XL"
  }
}

CSS:

#filters {
    width: 200px;
    height: 800px;
    border: 1px solid black;
    float: left;
    margin: 0;
}
.price-input {
    float: left;
}
.input-text {
    width: 50px;
   
}
.single-goods {
    width: 280px;
    height: 530px;
    border: 1px solid black;
    margin: 10px;
    float: left;
    text-align: center;
}

在loadGoods()函数中,您可以在插入数据之前对其进行过滤:

我写了一些伪代码-您应该可以用它来解决它:

// In the loop in loadGoods:
for (key in data) {
    if (!isMatch(data[key])) continue;

    // .. add to output
}

// Helper function
function isMatch(element) {
    let selectedCountry = getSelectedCountry();
    let allChecked = getAllCheckedCheckboxes();
    let priceFrom = getPrice();
    let priceTo = getPrice();

    return element.country == selectedCountry &&
            allChecked.indexOf(element.size) != -1 &&
            element.cost > priceFrom &&
            element.cost < priceTo;
}

您只需要解决以下问题(在google和stackoverflow的帮助下不难解决):

  • 如何获得一class所有选中的checkboxes
  • 如何获得的所选的选项select
  • 如何获取input元素的输入值

好吧,让我尝试帮助您前进。

这里有很多解决方案,但这应该可以帮助您继续前进。 我只包括尺寸和国家/地区代码。

如有任何疑问,请随时提出。

链接::

 var arrSize = ["S", "M", "L", "XL"]; var country = "all"; function defineCountry(el) { country = el.value || "all"; sumbitFilters(); } function defineSize() { // checking witch sizes has been checked //we make arrSize empty again arrSize = []; document.querySelectorAll("#filters .size :checked").forEach((elem) => { // we grab all size filters that has been checked and loop over to push the value to arrSize arrSize.push(elem.value); }); sumbitFilters(); return false; } function sumbitFilters() { //grab all item and check if they match condition document.querySelectorAll("#items div").forEach((elem) => { let testCountry = elem.dataset.country.split(",").some(function(c) { //this refers to the second parameter of Array.some function if (this.val === "all" || this.val === c) { return true; } return false; }, { val: country }); let testSize = elem.dataset.size.split(",").some(function(s) { //this refers to the second parameter of Array.some function if (this.val.indexOf(s) > -1) { return true; } return false; }, { val: arrSize }); // display or not based on the 2 condition above if (testCountry && testSize) { elem.style.display = "initial"; } else { elem.style.display = "none"; } }); } 
 <div id="filters"> <div class="country"> <h2> Country </h2> <select id="country" onchange="defineCountry(this)"> <option value="all"> All </option> <option value="turkey"> Turkey </option> <option value="china"> China </option> <option value="france"> France </option> <option value="italy"> Italy </option> </select> </div> <div class="size"> <h2> Size </h2> <div id="myDropdown"> <input type="checkbox" class="btn" value="S" checked="true" oninput="defineSize(this)"> S <br> <input type="checkbox" class="btn" value="M" checked="true" oninput="defineSize(this)"> M <br> <input type="checkbox" class="btn" value="L" checked="true" oninput="defineSize(this)"> L <br> <input type="checkbox" class="btn" value="XL" checked="true" oninput="defineSize(this)"> XL <br> </div> </div> </div> <div id="items" style="display:flex"> <!-- we use data attributes over here, this can be set like you did in your JSON request--> <div data-country="italy,france" data-size="M"><img src="https://loremflickr.com/150/150/dog"></div> <div data-country="china,turkey" data-size="S,M"><img src="https://loremflickr.com/150/150/house"></div> <div data-country="turkey" data-size="XL"><img src="https://loremflickr.com/150/150/cat"></div> </div> 

暂无
暂无

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

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