文本在 JS 中创建的元素上的内容不起作用?



我正在做一项学校任务,但我最近遇到了文本内容问题。我导入一个 JSON 文件并将数据用作 foreach。.js文件中没有错误,但我收到一个类型错误:无法设置未定义的属性"textContent",即使我使用 JSON 文件中的元素定义了属性?

当我删除带有 textContent 的两行时,我收到与 appendChild 属性类似的错误:无法读取 null 的属性"appendChild"。

如果我在我的forEach中登录 coffee.name,我确实会得到正确的名字。我猜我只得到一个名字,因为 forEach 由于进一步的错误而无法进一步循环。

我的js代码:

import './style.css';
import data from './assets/data/coffees.json';
const init = () => {
console.log(data);
createPriceList(data);
};
const createPriceList = coffees => {
const ul = document.querySelector('prices__list');
console.log(coffees);
coffees.coffees.forEach(coffee => {
if (coffee.plantbased === true) {
const price = document.createElement('li');
price.classList.add('price');
const a = document.createElement('a').classList.add('price__button');
const spanWrapper = document.createElement('span').classList.add('price__button__wrapper');
const spanName = document.createElement('span').classList.add('price__button__name');
const spanAmount = document.createElement('span').classList.add('price__button__amount');
const spanPlus = document.createElement('span').classList.add('price__button__plus');
spanName.textContent = coffee.name;
spanAmount.textContent = coffee.prices.medium;
ul.appendChild(price);
price.appendChild(a);
a.appendChild(spanWrapper);
spanWrapper.appendChild(spanName);
spanWrapper.appendChild(spanAmount);
a.appendChild(spanPlus);
}
});
};
init();

这是我尝试创建的 HTML(注释中的部分,其余部分已定义(:

<section class="prices highlight spaced">
<h2 class="visually-hidden">Price list</h2>
<ul class="prices__list">
<!--<li class="price">
<a class="price__button">
<span class="price__button__wrapper">
<span class="price__button__name">Oat Latte</span>
<span class="price__button__amount">&euro; 2</span>
</span>
<span class="price__button__plus">+</span>
</a>
</li> -->
</ul>
</section>

您正在尝试像这样将方法链接在一起:

const test = document.createElement('span').classList.add('price__button__name');
console.log(test.classList);

但是,您必须先创建元素,然后才能使用其classList或其他属性:

const test = document.createElement('span');
test.classList.add('price__button__name');
console.log(test.classList);

最新更新