首页 > 解决方案 > foreach 中的 textContent 不起作用,没有错误

问题描述

我正在做一个学校项目,但遇到了 textContent 问题。在 HandleClickbutton 函数内部,orderName 和 orderPrice 的 textContent 不起作用。我尝试在全球范围内进行文本内容,然后它确实有效。我想要做的是,当单击添加按钮时,代码会检查目标 ID 是否等于 JSON 中的咖啡 ID 之一。如果是这样,请根据 JSON 信息更改名称和价格。订单对象是一个计数器,每次点击一个目标,计数器就会上升,所以我知道每个项目有多少订单。

我没有收到任何错误,所以我不知道我哪里出错了。

import data from './assets/data/coffees.json';

const orders = {
  1: 0,
  2: 0,
  3: 0,
  4: 0,
  5: 0,
  6: 0,
  7: 0,
  8: 0
};

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 li = document.querySelector('.price');
      const a = document.createElement('a');
      a.classList.add('price__button');
      const spanWrapper = document.createElement('span');
      spanWrapper.classList.add('price__button__wrapper');
      const spanName = document.createElement('span');
      spanName.classList.add('price__button__name');
      const spanAmount = document.createElement('span');
      spanAmount.classList.add('price__button__amount');
      const spanPlus = document.createElement('span');
      spanPlus.classList.add('price__button__plus');
      spanPlus.setAttribute('id', coffee.id);
      spanName.textContent = coffee.name;
      spanAmount.textContent = '\u20AC';
      const price = coffee.prices.medium;
      const newPrice = price.toFixed(2); //add 2 decimals
      const finalPrice = newPrice.replace('.', ','); //replace . with ,
      spanAmount.textContent += finalPrice;
      spanPlus.textContent = '+';

      ul.appendChild(li);
      li.appendChild(a);
      a.appendChild(spanWrapper);
      spanWrapper.appendChild(spanName);
      spanWrapper.appendChild(spanAmount);
      a.appendChild(spanPlus);

      spanPlus.addEventListener('click', handleClickButton);

    }
  });
};


const handleClickButton = e => {
  document.querySelector('.emptystate').style.display = 'none';
  document.querySelector('.hide').style.display = 'initial';
  console.log(e.target.id);
  orders[e.target.id] ++;
  console.log(orders);

  data.coffees.forEach(coffee => {
    console.log(coffee.id);
    if (e.target.id === coffee.id) {
      const orderName = document.querySelector('.order__name');
      orderName.textContent = coffee.name;

      const orderPrice = document.querySelector('.order__price');
      orderPrice.textContent = coffee.prices.medium;
    }
  });
};


init();

我的html:

<!DOCTYPE html>
<html lang="nl">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="https://fonts.googleapis.com/css?family=Roboto:400,500&display=swap" rel="stylesheet">
  <title>The Plant-Based Barista</title>
</head>

<body>
  <main class="layout">
    <header class="header highlight spaced">
      <div class="header__titles">
        <a class="h2-like">
          The Plant-Based Barista
        </a>
        <h1 class="h1-like">What do you want<br> to order?</h1>
      </div>
      <img srcset="./assets/img/image_1.png 102w,
      ./assets/img/image_1@2x.png 204w" sizes="102px" src="./assets/img/image_1.png" alt="coffee">
    </header>
    <section class="prices highlight spaced">
      <h2 class="visually-hidden">Price list</h2>
      <ul class="prices__list">
        <li class="price" data-id="1"></li>
        <li class="price" data-id="2"></li>
        <li class="price" data-id="3"></li>
        <li class="price" data-id="4"></li>
      </ul>
    </section>
    <section class="content spaced">
      <h2 class="title_mini">Order</h2>
      <div class="orders__wrapper hide">
        <ul class="orders">
          <li class="order">
            <div class="order__name__wrapper">
              <span class="order__amount">{amount} X</span><span class="order__name">{drink.name}</span>
            </div>
            <div class="price__wrapper">
              <span class="order__price">&euro; {total}</span>
              <button class="remove">
                x
              </button>
            </div>
        </ul>
        <p class="total">
          <span class="total__label">Total</span>
          <span class="total__price">&euro; <span> 0,00</span></span>
        </p>
      </div>
      <div class="emptystate">
        <img srcset="./assets/img/coffee-maker.jpg 67w,
          ./assets/img/coffee-maker@2x.jpg 134w" sizes="67px" src="./assets/img/coffee-maker.jpg" alt="A coffee maker">

        <span class="emptystate__content">
          Please order something
          <span role="img" aria-label="Drunk emoji">
            
          </span>
        </span>
      </div>
    </section>
  </main>
  <footer class="nav_bar">
    <div class="nav_wrapper nav_active">
      <img srcset="./assets/img/home.png 28w" sizes="28px" src="./assets/img/home.png" alt="home">
      <p>Home</p>
    </div>
    <div class="nav_wrapper">
      <img src="./assets/img/about.png" alt="about">
      <p>About</p>
    </div>
    <div class="nav_wrapper">
      <img src="./assets/img/admin.png" alt="admin">
      <p>Admin</p>
    </div>
  </footer>
</body>

</html>

JSON:

    {
  "coffees": [
    {
      "id": 1,
      "name": "Oat Latte",
      "plantbased": true,
      "description": "Latte coffee with oat plant milk.",
      "prices": {
        "small": 2.5,
        "medium": 3.5,
        "large": 4.5,
        "extra_large": 5.5
      }
    },

标签: javascripthtml

解决方案


console.log (typeof e.target.id, typeof coffee.id, coffee.name) 

将告诉您需要在 JSON 中引用 coffee.id 以与始终为字符串的元素 id 进行比较。顺便说一句,我不建议使用数字作为 ID...

  "coffees": [{
    "id": "1", // was a number

const data = {
  "coffees": [{
    "id": "1",
    "name": "Oat Latte",
    "plantbased": true,
    "description": "Latte coffee with oat plant milk.",
    "prices": {
      "small": 2.5,
      "medium": 3.5,
      "large": 4.5,
      "extra_large": 5.5
    }
  }]
}

const orders = {
  1: 0,
  2: 0,
  3: 0,
  4: 0,
  5: 0,
  6: 0,
  7: 0,
  8: 0
};

const init = () => {
  createPriceList(data);
};

const createPriceList = coffees => {
  const ul = document.querySelector('.prices__list');

  coffees.coffees.forEach(coffee => {
    if (coffee.plantbased === true) {
      const li = document.querySelector('.price');
      const a = document.createElement('a');
      a.classList.add('price__button');
      const spanWrapper = document.createElement('span');
      spanWrapper.classList.add('price__button__wrapper');
      const spanName = document.createElement('span');
      spanName.classList.add('price__button__name');
      const spanAmount = document.createElement('span');
      spanAmount.classList.add('price__button__amount');
      const spanPlus = document.createElement('span');
      spanPlus.classList.add('price__button__plus');
      spanPlus.setAttribute('id', coffee.id);
      spanName.textContent = coffee.name;
      spanAmount.textContent = '\u20AC';
      const price = coffee.prices.medium;
      const newPrice = price.toFixed(2); //add 2 decimals
      const finalPrice = newPrice.replace('.', ','); //replace . with ,
      spanAmount.textContent += finalPrice;
      spanPlus.textContent = '+';

      ul.appendChild(li);
      li.appendChild(a);
      a.appendChild(spanWrapper);
      spanWrapper.appendChild(spanName);
      spanWrapper.appendChild(spanAmount);
      a.appendChild(spanPlus);

      spanPlus.addEventListener('click', handleClickButton);

    }
  });
};


const handleClickButton = e => {
  document.querySelector('.emptystate').style.display = 'none';
  document.querySelector('.hide').style.display = 'initial';
  //  console.log(e.target.id);
  orders[e.target.id]++;
  //  console.log(orders);

  data.coffees.forEach(coffee => {
    console.log(typeof e.target.id, typeof coffee.id, coffee.name)

    if (e.target.id === coffee.id) {
      const orderName = document.querySelector('.order__name');
      orderName.textContent = coffee.name;
      const orderPrice = document.querySelector('.order__price');
      orderPrice.textContent = coffee.prices.medium;
    }
  });
};


init();
<link href="https://fonts.googleapis.com/css?family=Roboto:400,500&display=swap" rel="stylesheet">
<title>The Plant-Based Barista</title>


<body>
  <main class="layout">
    <header class="header highlight spaced">
      <div class="header__titles">
        <a class="h2-like">
          The Plant-Based Barista
        </a>
        <h1 class="h1-like">What do you want<br> to order?</h1>
      </div>
      <img srcset="./assets/img/image_1.png 102w,
      ./assets/img/image_1@2x.png 204w" sizes="102px" src="./assets/img/image_1.png" alt="coffee">
    </header>
    <section class="prices highlight spaced">
      <h2 class="visually-hidden">Price list</h2>
      <ul class="prices__list">
        <li class="price" data-id="1"></li>
        <li class="price" data-id="2"></li>
        <li class="price" data-id="3"></li>
        <li class="price" data-id="4"></li>
      </ul>
    </section>
    <section class="content spaced">
      <h2 class="title_mini">Order</h2>
      <div class="orders__wrapper hide">
        <ul class="orders">
          <li class="order">
            <div class="order__name__wrapper">
              <span class="order__amount">{amount} X</span><span class="order__name">{drink.name}</span>
            </div>
            <div class="price__wrapper">
              <span class="order__price">&euro; {total}</span>
              <button class="remove">
                x
              </button>
            </div>
        </ul>
        <p class="total">
          <span class="total__label">Total</span>
          <span class="total__price">&euro; <span> 0,00</span></span>
        </p>
      </div>
      <div class="emptystate">
        <img srcset="./assets/img/coffee-maker.jpg 67w,
          ./assets/img/coffee-maker@2x.jpg 134w" sizes="67px" src="./assets/img/coffee-maker.jpg" alt="A coffee maker">

        <span class="emptystate__content">
          Please order something
          <span role="img" aria-label="Drunk emoji">
            
          </span>
        </span>
      </div>
    </section>
  </main>
  <footer class="nav_bar">
    <div class="nav_wrapper nav_active">
      <img srcset="./assets/img/home.png 28w" sizes="28px" src="./assets/img/home.png" alt="home">
      <p>Home</p>
    </div>
    <div class="nav_wrapper">
      <img src="./assets/img/about.png" alt="about">
      <p>About</p>
    </div>
    <div class="nav_wrapper">
      <img src="./assets/img/admin.png" alt="admin">
      <p>Admin</p>
    </div>
  </footer>


推荐阅读