You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

住宿费用计算JavaScript代码点击提交无响应,请求排查修复

修复你的住宿费用计算代码

我帮你排查出了代码里的几个关键问题,咱们一个个来解决:

问题分析

  • 元素ID不匹配:HTML里输入框的ID是pricePerNight和noNights,但你的JS代码里错误地用price和nights去获取输入值,导致根本拿不到用户输入的内容,这是按钮点击后没反应的核心原因。
  • 函数变量名不一致:calcDiscount函数的参数是numNights,但函数内部判断时用的是numberOfNights,变量未定义直接导致折扣计算失败。
  • 折扣逻辑错误:calcAmount里直接用cost - discount,但discount是折扣率(比如0.03),不是实际折扣金额,正确逻辑应该是先算折扣金额=原价×折扣率,再用原价减去折扣金额得到最终总价。
  • 初始化函数未执行:init函数用来绑定按钮点击事件,但页面加载时没有触发它,所以点击按钮不会调用processQuote。
  • 错误提示字符串拼接问题:错误提示里的文本缺少空格,显示会不美观,比如"The price10you entered"应该改成"The price 10 you entered"。

修复后的代码

JavaScript代码

function calcStayCost(pricePerNight, numberOfNights) {
    return pricePerNight * numberOfNights;
}

function calcDiscount(numNights) { // 移除无用的standardCost参数,仅需入住天数即可计算折扣率
    let dRate;
    if (numNights < 5) {
        dRate = 0;
    } else if (numNights >= 5 && numNights <= 10) {
        dRate = 0.03;
    } else {
        dRate = 0.05;
    }
    return dRate;
}

function calcAmount(cost, discountRate) {
    const discountAmount = cost * discountRate;
    return cost - discountAmount;
}

function validateInput(validNumber) {
    return validNumber > 0 && !isNaN(validNumber); // 新增非NaN判断,避免输入非数字内容
}

function processQuote() {
    // 修正:获取正确的输入框ID
    const pricePerNight = Number(document.getElementById('pricePerNight').value);
    const totalNights = Number(document.getElementById('noNights').value);

    const validPrice = validateInput(pricePerNight);
    const validNights = validateInput(totalNights);

    // 每次提交前清空之前的结果和提示,避免内容堆积
    document.getElementById('price').innerHTML = '';
    document.getElementById('discount').innerHTML = '';
    document.getElementById('amount').innerHTML = '';
    document.getElementById('priceErrorMessage').innerHTML = '';
    document.getElementById('nightsErrorMessage').innerHTML = '';

    if (validPrice && validNights) {
        const standardCost = calcStayCost(pricePerNight, totalNights);
        document.getElementById('price').innerHTML = `The standard cost of stay is: $${standardCost.toFixed(2)}`; // 保留两位小数符合货币展示规范

        const discountRate = calcDiscount(totalNights);
        const discountAmount = standardCost * discountRate;
        document.getElementById('discount').innerHTML = `The total discount amount is: $${discountAmount.toFixed(2)}`;

        const totalAmountDue = calcAmount(standardCost, discountRate);
        document.getElementById('amount').innerHTML = `The total amount due is: $${totalAmountDue.toFixed(2)}`;
    } else {
        if (!validPrice) {
            document.getElementById('priceErrorMessage').innerHTML = `The price ${pricePerNight} you entered is invalid, please enter a value greater than $0`;
        }
        if (!validNights) {
            document.getElementById('nightsErrorMessage').innerHTML = "The number of nights you entered is invalid, please enter a value of 1 or more";
        }
    }
}

function init() {
    const btn = document.getElementById('send');
    btn.onclick = processQuote;
}

// 页面加载时触发初始化,绑定按钮点击事件
window.onload = init;

HTML代码

<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="description" content="Quote calculator" />
    <meta name="keywords" content="quote, calculator, javascript, html" />
    <meta name="author" content="Mario Stavreski" />
    <title>Testing output</title>
    <script src="w4P1.js"></script>
</head>
<body>
    <header></header>
    <article>
        <h2> Accommodation Quote </h2>
        <form>
            <label> Price Per Night: <input type="text" id="pricePerNight" /> </label>
            <label> Number of Nights <input type="text" id="noNights" /> </label>
            <button type="button" id="send"> Submit </button>
        </form>
        <p id="price"></p>
        <p id="discount"></p>
        <p id="amount"></p>
        <p id="priceErrorMessage" style="color: red;"></p>
        <p id="nightsErrorMessage" style="color: red;"></p>
    </article>
    <footer><p>Produced by Mario Stavreski</p></footer>
</body>
</html>

额外优化说明:

  • 给错误提示添加了红色样式,更醒目直观
  • 金额显示保留两位小数,符合日常货币展示习惯
  • 每次提交前清空历史内容,避免页面信息混乱
  • 增强输入验证逻辑,防止非数字内容干扰计算

内容的提问来源于stack exchange,提问作者StavreskiM

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 10:02:42