如何在转换后的数字旁边输出货币类型



>我正在尝试让我的代码在转换后的数字旁边输出货币类型名称,例如欧元、日元和美元,但我似乎遇到了麻烦,任何帮助将不胜感激。

function tipCalculator() {
  var billAmt = document.getElementById("bill").value;
  var tipValue = document.getElementById("tipValue").value;
  if (billAmt === "" || tipValue == 0) {
    alert("Please Enter Value")
    return;
  }
  var total = (billAmt * tipValue);
  total = Math.round(total * 100) / 100;
  total = total.toFixed(2);
  document.getElementById("totalTip").style.display = "block";
  document.getElementById("tip").innerHTML = total;
  if (document.getElementById("USD")) {
    document.getElementById("tip").innerHTML = total + " USD";
  }
}
document.getElementById("totalTip").style.display = "none";
document.getElementById("calculate").onclick =
  function() {
    tipCalculator();
  }
<select id="tipValue">
      <option value="">--Please choose a currency--</option>
      <option value ="1.30353" id="USD">USD</option>
      <option value ="1.16158" id="Euro">Euro</option>
      <option value ="8.75747" id="Yen">Yen</option>
      <option value ="4.98785" id="Zloty">Zloty</option>
</select>

您需要做的是从您的货币选项(美元、欧元、日元、兹罗提等(创建一个数组,并在以下if语句中引用该数组而不是"USD"

if(document.getElementById("USD")){
    document.getElementById("tip").innerHTML = total + " USD";
    }

像这样:

if(document.getElementById("currency_array[]")){
    document.getElementById("tip").innerHTML = total + " currency_array[]";
    }

@elbrant 这仍然有同样的问题,因为您需要知道您在数组中的位置。您需要传递 id 才能使其动态化。因此,我会将您的选项变成点击事件,以便它可以传递其 id:

document.getElementById("option").onclick =
  function() {
    tipCalculator(this.id);
  }

不要忘记将参数添加到函数中。

在函数中,摆脱 if 语句并执行以下操作:

document.getElementById("tip").innerHTML = total + this.id;

最新更新