[英]is it possible to assign the textContent of an element to be HTML code in JS?
[英]textContent on created element in JS not working?
我正在處理學校任務,但最近遇到了 textContent 問題。 我導入 JSON 文件並將數據用作 foreach。 .js 文件中沒有錯誤,但我收到 typeError: cannot set property 'textContent' of undefined,即使我使用 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 (評論中的部分,定義了 rest):
<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">€ 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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.