css qureySelector找不到类名[重复]

k2arahey  于 2023-02-17  发布在  其他
关注(0)|答案(1)|浏览(137)
    • 此问题在此处已有答案**:

Why does jQuery or a DOM method such as getElementById not find the element?(6个答案)
昨天关门了。
我的类代码总是给我

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

这是我到目前为止编写的Java脚本

//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);
}

我觉得我错过了一些明显的,帮助这将是感激。
代码应该根据2个项目的总成本更改背景颜色,然后更改h3和p1文本以告诉用户它们的总成本。

xxslljrj

xxslljrj1#

您的script标记在创建元素之前运行。您可以通过将其移动到正文末尾来修复此问题。

<!DOCTYPE html>
<html>
<head>
    <title>CE05 QuertSelector</title>
</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>

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

相关问题