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

querySelector获取元素报错及JavaScript折扣逻辑问题求助

代码报错排查:Cannot set properties of null (setting 'className')

报错信息

SCRIPT.JS:24 Uncaught TypeError: Cannot set properties of null (setting 'className')
at SCRIPT.JS:24:47

需求说明

实现根据两件商品的总价切换页面背景色,并修改h3和p标签文本,显示用户的总价及折扣信息。


原代码

JavaScript代码

//Seting some variables to make coding easier
let userGreet = document.querySelector("#userGreet");
let userData = document.querySelector("#userData");

let userName = prompt("What is your name?");

alert("Hello "+userName+", Lets Calculate your purchase");

//Here we prompt the user for the price of there 2 items
let item1 = parseFloat(prompt("How Much it your first Item?"));
let item2 = parseFloat(prompt("How much is your second item?"));

//Now we add those items together to get the total
let total = item1 + item2;


//Now we will use if & elseif statements to see if the user gets a discount on their purchase 
if (_total => 100){
    let afterDiscount = total * .10;
    document.querySelector("body").className =  "discount";
    userGreet.innerHTML = "Hello " + userName + ", Here is your Total.";
    userData.innerHTML = "Your purchase total is $" + afterDiscount + ", which includes your 10% discount.";

} else if (_total => 50){
    let afterDiscount = total * .05;
    document.querySelector("body").className =  "discount";
    userGreet.innerHTML = "Hello " + userName + ", Here is your Total.";
    userData.innerHTML = "Your purchase total is $" + afterDiscount + ", which includes your 5% discount.";

} else if (total < 50){
    
    document.querySelector("body").className =  "nonDiscount";
    userGreet.innerHTML = "Hello " + userName + ", Here is your Total.";
    userData.innerHTML = "Your purchase total is $" + total;
}

HTML代码

<!DOCTYPE html>
<html>
<head>
    <title>CE05 QuertSelector</title>
    <script src="JS/SCRIPT.JS"></script>
</head>
<body class="body">
<link rel="stylesheet" href="CSS/STYLE.CSS"> 

<h1 id="topOf">QuerySelector</h1>
<h3 id="userGreet">Hello User</h3>
<p id="userData">let play with QuerySelector</p>

</body>
</html>

CSS代码

body {
    background-color: rgb(255, 255, 255);
  }
  
h1 {
    color: rgb(1, 1, 1);

  }
  
h3{
    Color: rgb(0, 0, 0);
  }
  
p {
    font-family: verdana;
    font-size: 20px;
  }

.discount{
  background-color: rgb(25, 225, 25) ;
}

.nonDiscount{
  background-color: rgb(216, 239, 12);
}

问题排查与修复

1. 脚本加载时机错误

HTML中script标签放在<head>里,页面尚未渲染<body>和目标h3、p标签,JS执行时document.querySelector找不到元素,返回null,导致设置className和innerHTML时触发报错。
修复:将script标签移至<body>末尾,确保DOM元素加载完成后再执行JS逻辑。

2. 变量名与运算符错误

  • 条件判断中使用了未定义的_total,应替换为实际声明的total;
  • 大于等于运算符误用为=>,正确写法是>=。

3. 折扣计算逻辑错误

原代码中afterDiscount = total * .10计算的是折扣金额而非最终总价,需改为total * 0.9(即总价减去10%折扣)或total - (total * 0.1)。

4. CSS链接位置错误

<link>标签应放在<head>内,否则样式可能加载延迟或失效。

5. 输入合法性处理

prompt可能返回null或非数字值,需处理item1和item2为NaN的情况,避免total变为NaN导致条件判断失效。


修复后的代码

修复后的HTML

<!DOCTYPE html>
<html>
<head>
    <title>CE05 QuerySelector</title>
    <link rel="stylesheet" href="CSS/STYLE.CSS"> 
</head>
<body class="body">
<h1 id="topOf">QuerySelector</h1>
<h3 id="userGreet">Hello User</h3>
<p id="userData">Let's play with QuerySelector</p>

<script src="JS/SCRIPT.JS"></script>
</body>
</html>

修复后的JavaScript

// 等待DOM加载完成再执行逻辑
document.addEventListener('DOMContentLoaded', function() {
    let userGreet = document.querySelector("#userGreet");
    let userData = document.querySelector("#userData");
    let body = document.querySelector("body");

    let userName = prompt("What is your name?");
    // 处理用户取消输入的情况
    if (!userName) userName = "User";

    alert(`Hello ${userName}, Let's Calculate your purchase`);

    // 获取商品价格并校验合法性
    let item1 = parseFloat(prompt("How much is your first item?"));
    while (isNaN(item1) || item1 < 0) {
        item1 = parseFloat(prompt("Please enter a valid positive number for the first item price:"));
    }

    let item2 = parseFloat(prompt("How much is your second item?"));
    while (isNaN(item2) || item2 < 0) {
        item2 = parseFloat(prompt("Please enter a valid positive number for the second item price:"));
    }

    let total = item1 + item2;
    let afterDiscount;

    // 判断折扣并更新页面内容
    if (total >= 100) {
        afterDiscount = total * 0.9; // 10%折扣后总价
        body.className = "discount";
        userGreet.textContent = `Hello ${userName}, Here is your Total.`;
        userData.textContent = `Your purchase total is $${afterDiscount.toFixed(2)}, which includes your 10% discount.`;
    } else if (total >= 50) {
        afterDiscount = total * 0.95; // 5%折扣后总价
        body.className = "discount";
        userGreet.textContent = `Hello ${userName}, Here is your Total.`;
        userData.textContent = `Your purchase total is $${afterDiscount.toFixed(2)}, which includes your 5% discount.`;
    } else {
        body.className = "nonDiscount";
        userGreet.textContent = `Hello ${userName}, Here is your Total.`;
        userData.textContent = `Your purchase total is $${total.toFixed(2)}.`;
    }
});

修复后的CSS

body {
    background-color: rgb(255, 255, 255);
}
  
h1 {
    color: rgb(1, 1, 1);
}
  
h3 {
    color: rgb(0, 0, 0); /* 修正Color为小写color,符合CSS规范 */
}
  
p {
    font-family: verdana;
    font-size: 20px;
}

.discount {
    background-color: rgb(25, 225, 25);
}

.nonDiscount {
    background-color: rgb(216, 239, 12);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 20:15:51