【问题标题】:textContent on created element in JS not working?JS中创建的元素上的textContent不起作用?
【发布时间】:2019-10-21 13:58:17
【问题描述】:

我正在处理一项学校任务,但最近遇到了一个 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(注释中的部分,其余部分已定义):

<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>

【问题讨论】:

    标签: javascript json


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢,我改了,但现在又收到 appendChild 错误:无法读取属性 'appendChild' of null。
    • @ArthurRobaeys 您是否更正了 all document.createElement 行?
    • 是的,所有这些都在 forEach 中。
    • 哪一行出错了(ul.appendChild()a.appendChild())?
    • 你是按类找元素,所以代码应该是:const ul = document.querySelector('.prices__list');(类名前加一个点)。
    猜你喜欢
    • 2019-06-15
    • 1970-01-01
    • 2011-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-18
    • 1970-01-01
    相关资源
    最近更新 更多