嗨,我是一个新的程序员,我正在使用免费代码夏令营学习js.我目前正在进行卡路里计数练习,我正在复制VsCode中的代码.我刚刚使用查询 Select 器向js添加了一个addEntry按钮,并收到以下错误:

未捕获的TypeError TypeErpeError:无法读取Null的属性(正在读取 ‘querySelectorAll’) 在addEntry-Filepath卡路里计数器.js 21

我是个彻头彻尾的新手,我不知道该找什么.

Index.html:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="device=device-width, initial-scale= 1.0" />\
        <link rel="stylesheet" href="C:\Users\babat\OneDrive\Desktop\Vs Code Projects\JsApps\Calorie Counter.css" />
        <title>Calorie Counter</title>
    </head>
    <body>
        <main>
            <h1>Calorie Counter</h1>
            <div class="container">
                <form id="calorie-counter">
                    <label for="budget">Budget</label>
                    <input id="budget" type="number" min="0" placeholder="Daily Calorie Counter" required />
                    <fieldset class="breakfast">
                        <legend>Breakfast</legend>
                        <div class="input-container"></div>
                    </fieldset>
                    <fieldset id="lunch">
                        <legend>Lunch</legend>
                        <div class="input-container"></div>
                    </fieldset>
                    <fieldset id="dinner">
                        <legend>Dinner</legend>
                        <div class="input-container"></div>
                    </fieldset>
                    <fieldset id="snacks">
                        <legend>Snacks</legend>
                        <div class="input-container"></div>
                    </fieldset>
                    <fieldset id="exercise">
                        <legend>Exercise</legend>
                        <div class="input-container"></div>
                    </fieldset>
                    <div class="controls">
                        <span>
                            <label for="entry-dropdown">Add food or exercise</label>
                            <select id="entry-dropdown" name="options">
                                <option value="breakfast" selected>Breakfast</option>
                                <option value="lunch">Lunch</option>
                                <option value="dinner">Dinner</option>
                                <option value="snacks">Snacks</option>
                                <option value="exercise">Exercise</option>
                            </select>
                            <button id="add-entry" type="button">Add Entry</button>
                        </span>
                    </div>
                    <div>
                        <button type="submit">Calculate Remaining Calories</button>
                        <button id="clear" type="button">Clear</button>
                    </div>
                </form>
                <div id="output" class="output hide"></div>
            </div>
        </main>
        <script src="C:\Users\babat\OneDrive\Desktop\Vs Code Projects\JsApps\Calorie Counter.js"></script>
    </body>
</html>

另请参阅以下内容:

:root {
    --light-grey: #f5f6f7;
    --dark-blue: #0a0a23;
    --fcc-blue: #1b1b32;
    --light-yellow: #fecc4c;
    --dark-yellow: #feac32;
    --light-pink: #ffadad;
    --dark-red: #850000;
    --light-green: #acd157;
  }
  
  body {
    font-family: "Lato", Helvetica, Arial, sans-serif;
    font-size: 18px;
    background-color: var(--fcc-blue);
    color: var(--light-grey);
  }
  
  h1 {
    text-align: center;
  }
  
  .container {
    width: 90%;
    max-width: 680px;
  }
  
  h1,
  .container,
  .output {
    margin: 20px auto;
  }
  
  label,
  legend {
    font-weight: bold;
  }
  
  .input-container {
    display: flex;
    flex-direction: column;
  }
  
  button {
    outline: none;
    cursor: pointer;
    text-decoration: none;
    background-color: var(--light-yellow);
    border: 2px solid var(--dark-yellow);
  }
  
  .clear {
    background-color: var(--light-pink);
    color: var(--dark-red);
    border-color: var(--dark-red);
  }
  
  button,
  input,
  select {
    min-height: 24px;
    color: var(--dark-blue);
  }
  
  fieldset,
  label,
  button,
  input,
  select {
    margin-bottom: 10px;
  }
  
  .output {
    border: 2px solid var(--light-grey);
    padding: 10px;
    text-align: center;
  }
  
  .hide {
    display: none;
  }
  
  .output span {
    font-weight: bold;
    font-size: 1.2em;
  }
  
  .surplus {
    color: var(--light-green);
  }
  
  .deficit {
    color: var(--light-pink);
  }

Java:

const calorieCounter = document.getElementById('calorie-counter');
const budgetNumberInput = document.getElementById('budget');
const entryDropdown = document.getElementById('entry-dropdown');
const addEntryButton = document.getElementById('add-entry');
const clearButton = document.getElementById('clear');
const output = document.getElementById('output');
let isError = false;

function cleanInputString(str) {
  const regex = /[+-\s]/g;
  return str.replace(regex, '');
}

function isInvalidInput(str) {
  const regex = /\d+e\d+/i;
  return str.match(regex);
}

function addEntry() {
  const targetInputContainer = document.querySelector(`#${entryDropdown.value} .input-container`);
  const entryNumber = targetInputContainer.querySelectorAll('input[type="text"]').length + 1;
  const HTMLString = `
  <label for="${entryDropdown.value}-${entryNumber}-name">Entry ${entryNumber} Name</label>
  <input type="text" id="${entryDropdown.value}-${entryNumber}-name" placeholder="Name" />
  <label for="${entryDropdown.value}-${entryNumber}-calories">Entry ${entryNumber} Calories</label>
  <input
    type="number"
    min="0"
    id="${entryDropdown.value}-${entryNumber}-calories"
    placeholder="Calories"
  />`;
  targetInputContainer.insertAdjacentHTML('beforeend', HTMLString);
}



addEntryButton.addEventListener("click", addEntry);

代码在freecode Camp应用程序的预览窗口中可以运行,但当我在Visual Studio代码中运行它时,它不能运行,并抛出错误.我try 将应用程序中的代码直接复制并粘贴到VS代码中,但仍然收到错误.

推荐答案

在HTMl中,您在第一个fieldset元素上添加了class="breakfast"

 <fieldset class="breakfast">
        <legend>Breakfast</legend>
        <div class="input-container"></div>
  </fieldset>

在您的脚本代码中,您试图通过id检索它,结果是targetInputContainer为空,这就是错误Cannot read properties of null的原因

  const targetInputContainer = document.querySelector(`#${entryDropdown.value} .input-container`);

解决方案是在您的html中将您的类="早餐"更改为id="早餐

<fieldset id="breakfast">
        <legend>Breakfast</legend>
        <div class="input-container"></div>
</fieldset>

Javascript相关问答推荐

为什么getRecord()会因为与_logger相关的错误而失败?(使用Hedera SDK)

D3多线图显示1线而不是3线

微软Edge Select 间隙鼠标退出问题

通过使用100%间隔时间来代表我们还剩多少时间来倒计时

使用续集和下拉栏显示模型属性

如何从JSON数组添加Google Maps标记—或者如何为数组添加参数到标记构造器

Google maps API通过API返回ZERO_RESULTS,以获得方向请求,但适用于Google maps

无法读取未定义错误的属性路径名''

我的角模板订阅后不刷新'

VUE 3捕获错误并呈现另一个组件

MarkLogic-earch.suggest不返回任何值

如何在FastAPI中为通过file:/URL加载的本地HTML文件启用CORS?

打字脚本中方括号符号属性访问和拾取实用程序的区别

删除元素属性或样式属性的首选方法

如何为仅有数据可用的点显示X轴标签?

在JavaScript中,有没有一种方法可以迭代字符串的词法标记?

TabNavigator和StackNavigator之间的Reaction Native中的导航问题

更新文本区域行号

更改管线时不渲染组件的react

Playwright:ReferenceError:browserContext未定义