`
<input type="number" id="qty">
<input type="button" onclick="add()" value="Add">
<script>
function add(){
qty = document.getElementById('qty').value
if(qty>0){
var tot = qty*25
document.write(tot)
}else{
qty = ""
alert("no")
}
}
</script>
'数量="'是谷歌上提到的正确方式。但对我不起作用。
尝试
document.getElementById("qty").value = "";
并将数量铸造到您的if 中的数字
if(Number(qty) > 0)
输入的值总是string
,请在您的条件下尝试这个:
if(Number(qty)>0){
...
}
使用以下代码清除输入
qty.value = "";
qty = ''
不起作用的原因是您已将输入的字符串值分配给该变量。将其设置为空字符串不会更改输入的值——您需要显式更改元素的值。
因此,首先要做几件事:
- 首先缓存元素通常很有用
- 删除内联JS,将其替换为
addEventListener
,并将其附加到按钮元素(一种更现代的方法) - 使用
<button>
元素而不是<input type="button">
- 由于各种原因,将总数指定给元素的文本内容/innerText,而不是
document.write
然后,当调用处理程序时,将输入的字符串值强制为一个数字,并在条件中使用它。如果数字小于零,则为输入值指定一个空字符串。
// Cache the elements
const qty = document.querySelector('#qty');
const result = document.querySelector('#result');
const button = document.querySelector('button');
// Add a listener to the button
button.addEventListener('click', add);
function add() {
// Coerce the input value to a number
const val = Number(qty.value);
if (val > 0) {
// Instead of `document.write` assign
// the total to the text content of an element
result.textContent = val * 25;
} else {
// Set the value of the qty element to
// an empty string
qty.value = '';
console.log('no');
}
}
#result { margin-top: 0.5em; }
<input type="number" id="qty">
<button type="button">Add</button>
<div id="result"></div>
如果您想在输入值时及时检查(正如我从问题中了解到的那样),则必须在<input type=" number" id="qty">
和事件上有一个侦听器'输入'。qty.addEventListener('input', (e)=>{ // .... make your validation })