我正在做一个按揭计算器,并试图清除所有输入时,清除按钮是按下。我好像没办法让它起作用。下面是我的html和JavaScript代码,我也尝试过设置输入= null,但没有成功。
HTML:
<div class="calculator">
<h1>Mortgage Calculator</h1>
<div class="input-container">
<label for="Loan-amount">Total Loan Amount</label>
<input type="number" name="Loan-amount" id="total" min="0">
</div>
<div class="input-container">
<label for="down-payment">Down payment</label>
<input type="number" name="Loan-amount" id="down" min="0">
</div>
<div class="input-container">
<label for="interest-rate">Interest rate %</label>
<input type="number" name="interest-rate" id="interest" min="0">
</div>
<div class="input-container">
<label for="loan-term">Loan Term (in years)</label>
<input type="number" name="loan-term" id="duration" min="0">
</div>
<div class="answer">
<h2>Estimated payment:</h2>
<p id="paragraph-value"></p>
</div>
<div class="button-container">
<button id="submitBtn">Calculate</button>
<button id="clearBtn">Clear</button>
</div>
<p id="alert"></p>
</div>JavaScript:
const clearBtn = document.querySelector("#clearBtn");
clearBtn.addEventListener("click", function (e) {
let total = document.getElementById("total").value;
let interest = document.querySelector("#interest").value;
let duration = document.querySelector("#duration").value;
let downPayment = document.querySelector("#down").value;
total = "";
interest = "";
duration = "";
downPayment = "";
});发布于 2022-07-15 11:48:44
您不是在为输入设置值,您只是过写了变量的值:
total = "";要设置输入的值,可以在输入上设置.value属性:
document.getElementById("total").value = "";例如:
const clearBtn = document.querySelector("#clearBtn");
clearBtn.addEventListener("click", function (e) {
document.getElementById("total").value = "";
});<input type="number" id="total" />
<button id="clearBtn">Reset</button>
在更一般的层次上,您似乎对这两件事之间的区别感到困惑:
var total = document.getElementById("total").value;
total = "";以及:
var total = document.getElementById("total");
total.value = "";在第一种情况下,变量保存了值本身的副本,然后将变量重新赋值给一个新值。这对元素没有任何影响。
但是在第二种情况下,变量保存对元素的引用,并且您正在更新该元素的属性。
https://stackoverflow.com/questions/72993484
复制相似问题