因此,我的问题是如何为HTML输入添加功能calculate()来动态更改税款输入。例如,如果我在收入字段中输入10000,则税应显示3500,如果我在财富字段中另外添加10000,则税应显示5000。

HTML:



var income = document.getElementById('income').value;
var wealth = document.getElementById('wealth').value;
var tax = document.getElementById('tax');

function calculate() {
  tax.innerHTML = (0.35 * income) + (0.25 * wealth);
}

<div class="row">
  <div class="col1">
    <label for="income">Income:</label>
  </div>
  <div class="col2">
    <input type="number" name="income" min="0" id="income" oninput="calculate()" required><br>
  </div>
</div>

<div class="row">
  <div class="col1">
    <label for="wealth">Wealth:</label>
  </div>
  <div class="col2">
    <input type="number" name="wealth" min="0" id="wealth" oninput="calculate()" required><br>
  </div>
</div>

<div class="row">
  <div class="col1">
    <label for="tax">Tax:</label>
  </div>
  <div class="col2">
    <input type="number" name="tax" min="0" id="tax" disabled>
  </div>
</div>

最佳答案

var incomeEl = document.getElementById('income')
var wealthEl = document.getElementById('wealth')
var taxEl    = document.getElementById('tax');

function calculate() {
  var incomeTax = 0.35 * incomeEl.value;
  var wealthTax = 0.25 * wealthEl.value;
  var tax =  incomeTax + wealthTax;

  // round with 2 decimal places
  taxEl.value = Math.round(tax * 100) / 100;
}

incomeEl.addEventListener('input', calculate);
wealthEl.addEventListener('input', calculate);

<div class="row">
  <div class="col1">
    <label for="income">Income:</label>
  </div>
  <div class="col2">
    <input type="number" name="income" min="0" id="income" required><br>
  </div>
</div>

<div class="row">
  <div class="col1">
    <label for="wealth">Wealth:</label>
  </div>
  <div class="col2">
    <input type="number" name="wealth" min="0" id="wealth" required><br>
  </div>
</div>

<div class="row">
  <div class="col1">
    <label for="tax">Tax:</label>
  </div>
  <div class="col2">
    <input type="number" name="tax" min="0" id="tax" disabled>
  </div>
</div>

关于javascript - 使用JavaScript计算税款,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52874066/

10-12 15:59