anli-筛选商品

2021-04-21  本文已影响0人  新苡米

1 定义数组对象数据

var data = [{
            id: 1,
            pname: '小米',
            price: 3999
        }, {
            id: 2,
            pname: 'oppo',
            price: 999
        }, {
            id: 3,
            pname: '荣耀',
            price: 1299
        }, {
            id: 4,
            pname: '华为',
            price: 1999
        }, ];

2 使用forEach遍历数据并渲染到页面中

data.forEach(function(value) {
  var tr = document.createElement('tr');
  tr.innerHTML = '<td>' + value.id + '</td><td>' + value.pname + '</td><td>' + value.price + '</td>';
  tbody.appendChild(tr);
 });

3 根据价格筛选数据

  1. 获取到搜索按钮并为其绑定点击事件
search_price.addEventListener('click', function() {
});

2 使用filter将用户输入的价格信息筛选出来

search_price.addEventListener('click', function() {
      var newDate = data.filter(function(value) {
        //start.value是开始区间
        //end.value是结束的区间
        return value.price >= start.value && value.price <= end.value;
      });
      console.log(newDate);
 });

3 将筛选出来的数据重新渲染到表格中
1. 将渲染数据的逻辑封装到一个函数中

function setDate(mydata) {
      // 先清空原来tbody 里面的数据
  tbody.innerHTML = '';
  mydata.forEach(function(value) {
    var tr = document.createElement('tr');
    tr.innerHTML = '<td>' + value.id + '</td><td>' + value.pname + '</td><td>' + value.price + '</td>';
      tbody.appendChild(tr);
  });
 }

2 将筛选之后的数据重新渲染

 search_price.addEventListener('click', function() {
     var newDate = data.filter(function(value) {
     return value.price >= start.value && value.price <= end.value;
     });
     console.log(newDate);
     // 把筛选完之后的对象渲染到页面中
     setDate(newDate);
});

4 根据商品名称筛选

  1. 获取用户输入的商品名称
  2. 为查询按钮绑定点击事件,将输入的商品名称与这个数据进行筛选
 search_pro.addEventListener('click', function() {
     var arr = [];
     data.some(function(value) {
       if (value.pname === product.value) {
         // console.log(value);
         arr.push(value);
         return true; // return 后面必须写true  
       }
     });
     // 把拿到的数据渲染到页面中
     setDate(arr);
})
上一篇 下一篇

猜你喜欢

热点阅读