【问题标题】:How to create a class that will manage goods in JS?如何在 JS 中创建一个管理商品的类?
【发布时间】:2019-05-17 12:24:35
【问题描述】:

我不知道如何创建一个管理货物的类。 1.按价格排序 2. 按名称排序

我创建了一个创建对象的构造函数。

class Products {
        constructor(name,price,description,img){
            this.name = name;
            this.price = price;
            this.description = description;
            this.img = img;
        }
    }
    var nike = new Products("Nike", 100, "new-shoes","img/nike.png");
    var adidas = new Products("Adidas", 120, "classic-shoes","img/adidas.png");
    var puma = new Products("Puma",150,"new-shoes","img/puma.png");
    var jordan = new Products("Jordan", 170, "outlet-shoes", "img/jordan.png");
    var converse = new Products("Converse",70,"outlet-shoes","img/convrse.png")
    var nikeAirMax = new Products("Nike Air Max", 200, "shoes","img/nikeAirMax.png");
    var newBal = new Products("New Balance 990",179,"new-shoes","img/newBal.png");
    var arrGoods = [nike,adidas,puma,jordan,nikeAirMax,converse,newBal];

然后创建了一个在 HTML 文件中显示商品的函数。

 function addGoods(item){
        for (let i = 0; i<arrGoods.length; i++){
                document.getElementById("products").innerHTML += `<div class="info-goods">
                <div class="img"><img src=${item[i].img}></div>
                <div class="name">${item[i].name}</div>
                <div class="price">${item[i].price}</div>
                <div class="description">${item[i].description}</div>
               </div>`
            }
    }
    addGoods(arrGoods);

创建的按价格和名称排序的函数

 function sortByPrise() {
        var div = document.querySelector("#products");
        if (div){
            div.innerHTML = '';
            this.PriseSort(arrGoods);
            addGoods(arrGoods);
        };

    }

    function sortByName() {
        var div = document.querySelector("#products");
        if (div){
            div.innerHTML = '';
            nameSort(arrGoods);
            addGoods(arrGoods);
        };
    }

    function PriseSort(arr){
        arr.sort(function(a,b){
            return a.price - b.price;
        });
    };

    function nameSort(arr){
        arr.sort(function(a,b){
            if(a.name > b.name){
                return 1;
            }
            if (a.name < b.name){
                return -1;

如何将这些函数添加到另一个类(例如,Menedger 类)

【问题讨论】:

    标签: javascript function class


    【解决方案1】:
    1. 将所有数据添加到对象数组中。
    2. 将选择器字符串和对象数组传递给构造函数。选择器用于&lt;table&gt;(表格比 div 好得多,但如果首选 div,则可以轻松更改)
    3. 添加一个从给定对象数组中添加行的方法。 请参阅演示中的 .addRows()
    4. 添加一个对对象数组进行排序并将其传递给.addRows() 的方法。 请参阅演示中的.sortCol()
    5. 作为奖励,&lt;th&gt; 将在单击时按列排序。回调不是class 的一部分,因为它超出了问题的范围。

    const items = [
      {name: "Nike", price: 100, desc: "new-shoes", img: "https://www.iconsdb.com/icons/preview/red/nike-xxl.png"},
      {name: "Adidas", price: 120, desc: "classic-shoes", img:"https://www.vouchercodes.co.uk/static/v10/images/merchant/logo/128px/1524_160119151356.png"},
      {name: "Puma",price: 150,desc: "new-shoes", img:"https://www.freepnglogos.com/uploads/puma-logo-png-1.png"},
      {name: "Jordan", price: 170, desc: "outlet-shoes",  img:"https://www.svgimages.com/svg-image/s8/air-jordan-logo-256x256.png"},
      {name: "Converse",price: 70,desc: "outlet-shoes", img:"https://d13genyhhfmqry.cloudfront.net/widget/mp_340806_2019-04-06-01-57-52-000851.jpg"},
      {name: "Nike Air Max",price:  200,desc:  "shoes", img:"https://www.iconsdb.com/icons/preview/red/nike-xxl.png"},
      {name: "New Balance 990",price: 179,desc: "new-shoes", img:"https://www.vouchercodes.co.uk/static/v10/images/merchant/logo/128px/4484_160309151253.png"}];
      
    class Products {
      constructor(selector, items) {
        this.table = document.querySelector(selector);
        this.items = [...items];
      }
    
      addRows(array) {
        const rng = document.createRange();
        rng.selectNodeContents(this.table);
        rng.deleteContents();
        for (let item of array) {
          let row = `
            <tr>
              <td><img src='${item.img}' width='50'></td>
              <td>${item.name}</td>
              <td>${item.price}</td>
              <td>${item.desc}</td>
            </tr>`;
          this.table.insertAdjacentHTML('beforeend', row);
        }
      }
    
      sortCol(key = 'name', descending = false) {
        if (this.items[0].hasOwnProperty(key)) {
          const compare = key => {
            return (a, b) => {
              if (a[key] < b[key]) return descending ? 1 : -1;
              if (a[key] > b[key]) return descending ? -1 : 1;
              return 0;
            };
          };
          let sorted = this.items.sort(compare(key));
          this.addRows(sorted);
        }
        return false;
      }
    
    }
    const shoes = new Products('.main', items);
    shoes.addRows(items);
    const head = document.querySelector('.head');
    
    function callback(e) {
      const clicked = e.target;
      if (clicked.matches('th')) {
        let key = clicked.className;
        if (clicked.dataset.dir === '1') {
          shoes.sortCol(key, true);
          clicked.dataset.dir = '0';
        } else {
          shoes.sortCol(key);
          clicked.dataset.dir = '1';
        }
      }
      return false;
    }
    head.addEventListener('click', callback);
    <table class='catalog'>
      <thead class='head'>
        <tr>
          <th class='name' data-dir='0' colspan='2'>Name</th>
          <th class='price' data-dir='0'>Price</th>
          <th class='desc' data-dir='0'>Desc</th>
        </tr>
      </thead>
      <tbody class='main'></tbody> 
     </table>

    【讨论】:

      【解决方案2】:

      我不会在产品类别中制作产品。只需保留产品类,例如:

      class Products {
              constructor(name, price, description, img){
                  this.name = name;
                  this.price = price;
                  this.description = description;
                  this.img = img;
              }
          }
      }
      

      然后你可以创建一个Manager类:

      class Manager {
          constructor() {
             this.products = this._createProducts()
          }
      
          _createProducts() {
              let nike = new Products("Nike", 100, "new-shoes","img/nike.png");
              let adidas = new Products("Adidas", 120, "classic-shoes","img/adidas.png");
              return [nike, adidas]
          }
      
          sortByName() {
             this.products.sort(function(prod1, prod2) {
                return prod1.name - prod2.name;
             });
          }
      
          getHTMLRepresentation() {
             productsHTML = this.products.map(function(product) {
                  // return html for each product in the array
                  return `<div class="info-goods">
                  <div class="img"><img src=${item[i].img}></div>
                  <div class="name">${item[i].name}</div>
                  <div class="price">${item[i].price}</div>
                  <div class="description">${item[i].description}</div>
                 </div>`
             )));
             return productsHTML;
          }
      }
      

      现在只需创建一个管理器类的实例并在其上调用函数:

      Manager manager = new Manager();
      manager.sortByName()
      // call a function to create html..
      document.querySelector("#products").innerHTML = manager.getHTMLRepresentation();
      

      【讨论】:

        猜你喜欢
        • 2015-05-18
        • 1970-01-01
        • 1970-01-01
        • 2021-09-21
        • 2019-03-17
        • 2019-11-27
        • 2019-06-24
        • 2015-01-16
        • 2013-02-06
        相关资源
        最近更新 更多