转换数组对象及其重写的函数

时间:2019-07-18 09:20:13

标签: javascript

在选择一种货币以根据其选择的价格转换所有价格产品,然后捍卫页面中的更改

我希望在选择硬币时将大块中所有产品的总和转换成每个产品的总和

该函数必须使用没有jQuery的javascript Vanilla编写

这是对象列表

let productsList = [
  {
    imageURL: "https://s12emagst.akamaized.net/products/8096/8095064/images/res_689070343515d1e2bcd294526b17f3c8_200x200_gnvo.jpg",
    discount: "-15%",
    name: "Monitor LFD PHILIPS 4k",
    brand: "philips",
    colors: "black",
    stoc: "out stoc",
    review: "",
    type: "monitor",
    price: 70000
  },
  {
    imageURL: "https://s12emagst.akamaized.net/products/22044/22043004/images/res_b6ecd7bc761b9d80fcefe28923b1b756_200x200_59vo.jpg",
    discount: "",
    name: "Monitor LED Dell Curbat 4k",
    brand: "dell",
    colors: "black",
    stoc: "on stoc",
    review: "",
    type: "monitor",
    price: 49000
  }];

这是创建卡片的功能

function createCard(product) {
  let card = document.createElement('div');
  card.className = 'card';

  let box_d = document.createElement('div');
  box_d.className = 'box-d';
  box_d.innerHTML = product.discount;
  if (product.discount !== "") {
    card.appendChild(box_d);
  }

  let box_h = document.createElement('div');
  box_h.className = 'box-h';
  box_h.innerHTML = '<i class="fas fa-2x fa-heart" onclick="heartSlide()"></i>';
  card.appendChild(box_h);

  let image = document.createElement('img');
  image.className = 'card-img';
  image.src = product.imageURL;
  card.appendChild(image);

  let review = document.createElement('div');
  review.className = 'p-info';
  review.innerHTML = 'Review: <span class="star"><i class="fas fa-star"></i><i class="fas fa-star"></i><i class="fas fa-star"></i><i class="fas fa-star"></i><i class="fas fa-star"></i></span>';
  card.appendChild(review);

  let name = document.createElement('div');
  name.className = 'p-info';
  name.innerHTML = product.name;
  card.appendChild(name);

  let stoc = document.createElement('div');
  stoc.className = 'p-info';
  stoc.innerHTML = `Stoc: ${product.stoc}`;
  card.appendChild(stoc);

  let price = document.createElement('div');
  price.className = 'p-info';
  price.innerHTML = `Price: ${product.price} RON`;
  card.appendChild(price);

  let button = document.createElement('button');
  button.className = 'add-btn';
  button.innerHTML = 'Add to cart <i class="fas fa-shopping-cart an"></i>';
  card.appendChild(button);

  return card;
}
productsList.forEach(product => document.body.append(createCard(product)));

1 个答案:

答案 0 :(得分:0)

您可以创建一个乘数对象,在其中添加受支持的货币和乘数。

例如, 如果您的基本货币为RON,那么:

const curMap = {
  RON: 1,
  USD: 0.24
}
function createCard(product, currency) {
   ...
   let price = document.createElement('div');
   price.className = 'p-info';
   price.innerHTML = `Price: ${product.price*curMap[currency]} ${currency}`;
   card.appendChild(price);
   ...
}

现在,您只需清除产品部分并重新生成卡即可。

productsList.forEach(product => document.body.append(createCard(product, "RON")))