首页 > 解决方案 > 如果 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();

});

标签: javascript

解决方案


您正在将值分配给常量变量,因此请使用

let numPeople = document.getElementById('numOfpeople').value;

推荐阅读