javascript - 如果 Statement 没有设置指定的值
问题描述
在我拔头发之前问。
下面的代码不起作用。如,如果在该输入字段中未输入任何内容,则不会将 numPeople变量的值设置为 1。我对它的编码与我见过的其他人的代码没有什么不同。
if (numPeople === "" || numPeople <= 1) {
numPeople = 1;
}
声明如下:
const numPeople = document.getElementById('numOfpeople').value;
最后整个代码是:
//function that calculates the tip
function calculateTip() {
//define the variables
const amount = document.getElementById('amount').value;
const serviceQual = document.getElementById('serviceQual').value;
const numPeople = document.getElementById('numOfpeople').value;
const output = document.getElementById('outputP');
//validation
if (amount == '') {
alert('Please Enter a Number');
return;
}
if (numPeople === "" || numPeople <= 1) {
numPeople = 1;
}
//calculation
var tipTotal = (amount * 0.15 * serviceQual) / numPeople;
//ui element
output.innerHTML = tipTotal;
}
//function that calls the tip function
document.getElementById('enter').addEventListener('click', function() {
calculateTip();
});
解决方案
您正在将值分配给常量变量,因此请使用
let numPeople = document.getElementById('numOfpeople').value;
推荐阅读
- c++ - static_cast 到一个结构类型来访问它的所有成员变量
- c++ - `LoadLibraryExW` 从`NtMapViewOfSection` 触发异常`0xC0000023`
- microsoft-graph-api - 有没有办法轻松查看 Azure/Microsoft Graph webhook 的调度是否有问题?
- java - 将 Immutable 转换为可变列表 Java,还有其他选择吗?
- sql-server - SQL Server:返回表中包含多个字符串的行
- c# - .net core EF core 多对多插入
- r - 将新数据放入R中的旧数据框中
- mysql - 使用计数大小写且列为空时如何返回“0”之类的值?
- excel-formula - 如何根据 Id 列将行转置为列
- javascript - 如何打印系列 1、3、4、6、7、8、10、11、12、13、15?