温馨提示:本文翻译自stackoverflow.com,查看原文请点击:html - Javascript

html - Java脚本

发布于 2020-03-28 23:37:03

因此,我想计算用户添加到购物车中的商品数量,并打印所有选定商品的总费用。计算项目数量是可以正常工作的,但是我正在努力找出如何获取与用户选择选择的每个项目相关的特定成本,并将所有这些项目的总和(代表变量)加在一起totalCost

For example, if the user clicks Add next to the iMac as well as Add next to the Windows PC, the total cost should be 2000 + 1300 = 3300. In the calculate() function, I attempted to iterate through all the items under the electronics department and check if the user clicked a button next to a certain item but it messed up my program which is why I commented the function out. Similar to the count variable, I'm trying to successfully get the total cost to update every time the user chooses to add something to their cart. Any guidance would be appreciated.

let count = 0;
let totalCost = 0;

function init() {
  count = 0;
  let button = document.getElementById("but");
  button.onclick = buttonClicked;
}

function buttonClicked() {
  count++;
  let div = document.getElementById("coutner");
  div.innerHTML = "You have " + count + " items and a total cost of $" + totalCost;
}

function showOptions(el) {
  let userPicked = el.value;
  var div = document.getElementById("div");
  if (userPicked != 'none') {
    var newContent = (electronics.store);
    newContent += '<div>';
    Object.keys(electronics.inventory).forEach(key => {
      newContent += key;
      newContent += '<div>';
      var items = Object.values(electronics.inventory[key]);
      items.forEach(item => {
        newContent += '<div>';
        newContent += `&nbsp; <span class="brand"> ${item.brand} </span>  <span class="price">$${item.cost}</span>`;
        newContent += `<input type=button value="Add" onclick="add(this)"/>`
        newContent += '</div>';
      });
      newContent += '</div>';
    });
    newContent += '</div>';
    div.innerHTML = newContent;
  }
}

function add(add) {
  console.clear();
  console.log(add.closest('div').textContent.trim());
  buttonClicked();
}


let electronics = {
  store: "Mike's Computers",
  inventory: {
    "Laptops": {
      0: {
        brand: "iMac",
        cost: 2000
      },
      1: {
        brand: "Dell",
        cost: 600
      }
    },
    "Computers": {
      2: {
        brand: "Windows PC",
        cost: 1300
      }
    }
  }
};
<div>
  <h1>Welcome</h1>
</div><br />
<div class="dropdown">
  <form>
    <select name="list" id="list" accesskey="target" onchange="showOptions(this); buttonClicked(this)">
      <option value="none">Select a restaurant</option>
      <option value="Electronics">Electronics</option>
    </select>
    <input type=button id="but" value="Select" onclick="showOptions(); buttonClicked()" />
    <div><mark id="coutner"></mark></div>
  </form>

</div>
<div id="div"></div>

I kept getting a formatting error when trying to show my comment so here it is separately (it was in the js file below init())

/*
function calculate(){
    if(userPicked == 'Electronics'){
        Object.keys(electronics.menu).forEach(key => {
             var items = Object.values(electronics.menu[key]);
               items.forEach(item => {
                  if(buttonClicked(){
                      totalCost += item.cost;
                  }
             });
        }); 
    }
}
*/

查看更多

查看更多

提问者
Grayish
被浏览
18
43.2k 2020-01-31 18:35

您可以通过将项目成本传递给add()函数来修复代码

另外,我已经将您的函数重命名为buttonClicked它的实际功能-更新显示。

始终尝试保持功能整洁,并且一次只能做一件事。通过将count++更新功能从更新功能移至它实际所属的位置(add功能),您可以分离功能,还可以修复显示屏中的一次性错误。

let count = 0;
let totalCost = 0;
let div = document.getElementById("coutner");

function init() {
  count = 0;
  let button = document.getElementById("but");
  button.onclick = updateDisplay;
}

function updateDisplay() {
  div.innerHTML = `You have ${count} items and a total cost of $${totalCost}`;
}

function showOptions(el) {
  let userPicked = el.value;
  var div = document.getElementById("div");
  if (userPicked != 'none') {
    var newContent = (electronics.store);
    newContent += '<div>';
    Object.keys(electronics.inventory).forEach(key => {
      newContent += key;
      newContent += '<div>';
      var items = Object.values(electronics.inventory[key]);
      items.forEach(item => {
        newContent += `
<div>&nbsp;
  <span class="brand"> ${item.brand}</span>
  <span class="price">$${item.cost}</span>
  <input type=button value="Add" onclick="add(this,${item.cost})"/>
</div>`;
      });
      newContent += '</div>';
    });
    newContent += '</div>';
    div.innerHTML = newContent;
  }
}

function add(element,cost) {
  console.clear();
  totalCost += parseInt(cost);
  count++;
  console.log(element.closest('div').textContent.trim());
  updateDisplay();
}


let electronics = {
  store: "Mike's Computers",
  inventory: {
    "Laptops": {
      0: {
        brand: "iMac",
        cost: 2000
      },
      1: {
        brand: "Dell",
        cost: 600
      }
    },
    "Computers": {
      2: {
        brand: "Windows PC",
        cost: 1300
      }
    }
  }
};
<div>
  <h1>Welcome</h1>
</div><br />
<div class="dropdown">
  <form>
    <select name="list" id="list" accesskey="target" onchange="showOptions(this); updateDisplay(this)">
      <option value="none">Select a restaurant</option>
      <option value="Electronics">Electronics</option>
    </select>
    <input type=button id="but" value="Select" onclick="showOptions(); updateDisplay()" />
    <div><mark id="coutner"></mark></div>
  </form>

</div>
<div id="div"></div>

发布
问题

分享
好友

手机
浏览

扫码手机浏览