为什么将变量分配为null?

时间:2019-12-27 12:27:45

标签: javascript variables

当我尝试运行此代码时

let addToy = false;
const toyCollection = document.getElementById('toy-collection');

document.addEventListener("DOMContentLoaded", ()=>{
  const addBtn = document.querySelector('#new-toy-btn')
  const toyForm = document.querySelector('.container')
  addBtn.addEventListener('click', () => {
    // hide & seek with the form
    addToy = !addToy
    if (addToy) {
      toyForm.style.display = 'block'
    } else {
      toyForm.style.display = 'none'
    }
  })

  loadToys();

})

function loadToys(){
  function createToyCard(toy) {
    const div = document.createElement('div');
    div.className = 'card';
    div.innerHTML = 
    `<h2>${toy.name}</h2>
    <img src=${toy.image} class="toy-avatar" />
    <p>${toy.likes} Likes </p>
    <button class="like-btn">Like <3</button>`;

    return div;
  };

  function appendAllToys(array) {
    array.forEach(element => {
      const div = createToyCard(element);
      toyCollection.appendChild(div);
    });
  };

  fetch('http://localhost:3000/toys')
  .then(resp => resp.json())
  .then(json => appendAllToys(json));
}

toyCollection变量似乎是null。我也收到以下错误

index.js:37 Uncaught (in promise) TypeError: Cannot read property 'appendChild' of null
    at index.js:37
    at Array.forEach (<anonymous>)
    at appendAllToys (index.js:35)
    at index.js:43

但是,我尝试在document.getElementById('toy-collection')函数中将代码不是作为变量运行,而是作为appendAllToys()运行,并且可以正常工作。这是什么问题?

0 个答案:

没有答案