简体   繁体   中英

create and add “li” element after click

In an exercise, I have created a new element li after each click of my button. It doesn't work. In the console it reports "li is not defined". What did I do wrong?

My code:

const btn = document.querySelector("button");
let number = 1;
const ul = document.querySelector("ul");
const fcn = function() {
  const li = document.createElement('li');
  li.textContent = number;

}

if (number % 3 == 0) {
  li.classList.add('big');
}


ul.appendChild(li);
number += 2;

btn.addEventListener("click", fcn);

try this:

 const btn = document.querySelector("button");
 let number = 1;
 const ul = document.querySelector("ul");
 const fcn = function () {
 const li = document.createElement('li');
 li.textContent = number;



if (number % 3 == 0) {
li.classList.add('big');
}


ul.appendChild(li);
number += 2;

}
btn.addEventListener("click", fcn);   

This problem is related to closures in javascript. li is not accessible outside function fcn .

following code should solve your problem.

const btn = document.querySelector("button");
let number = 0;
const ul = document.querySelector("ul");
const fcn = function () {
   number += 1;
   const li = document.createElement('li');
   li.textContent = number;
   ul.appendChild(li);

   if (number % 3 == 0) {
      li.classList.add('big');
   }

}
btn.addEventListener("click", fcn);

li is defined within anonymous function.

When you define a variable/constant within function it's local to that function and can't be accessed outside it. It has function level scope.

To fix your code either define li outside of function at global scope or move the piece of code that use it within function itself as follows:

  const btn = 
  document.querySelector("button");

  let number = 1;
  const ul = 
  document.querySelector("ul");

  const fcn = function () {
  const li = 
  document.createElement('li');
  li.textContent = number;

  if(number % 3 == 0){
     li.classList.add('big');
  }

  ul.appendChild(li);
  number += 2;
}
  btn.addEventListener("click", fcn);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM