简体   繁体   中英

Why am I getting “Cannot read property of html undefined”?

I am building a simple counter to practice closures in JS, and I can't seem to get past this error. In my mind setting the variable elem to the id of canv should work, but something is obviously not connecting. What am I doing wrong here?

My HTML:

<body>
  <div id="canv">

  </div>
</body>

My JS:

function setup(delay) {
  var el = document.getElementById('canv');

  counterFn(el, delay);
}

function counterFn(el, delay) {
  var counter = 0;

  setInterval(getTime, delay);

  function getTime(el) {
    el.innerHTML(counter);
    counter++;
  }
}

setup(500);

This all feels very elementary but I can't seem to figure out what I am doing wrong.

Here's a JS fiddle. https://jsfiddle.net/8sjaqdrh/2/

The thing that caused the error is because el is not defined within the scope of getTime .

In getTime's parent scope counterFn , el is defined because you gave it a value when calling it in counterFn(el, delay) inside setup function, which is el = document.getElementById('canv') .

However in the scope of getTime , you did not provide el with a value. So el becomes undefined .

Another problem with the code is the incorrect usage of innerHTML .

Just removing the parameter from function getTime(el){... to function getTime(){... will do.

As for innerHTML , it is not a function. So it can't be called like innerHTML(counter) .

The correct way is to directly assign a value to it like innerHTML = counter .

 function setup(delay) { var el = document.getElementById('canv'); counterFn(el, delay); } function counterFn(el, delay) { var counter = 0; setInterval(getTime, delay); // Corrected code: function getTime() { el.innerHTML = counter; counter++; } /* Your code function getTime(el){ el.innerHTML(counter); counter++; } */ } setup(500); 
 <div id="canv"></div> 

One potential issue here is that your trying to get the canvas before it exist in the DOM, you will want to wrap your code in a window.onload event to prevent that from happening.

Next for the code bellow here:

setInterval(getTime, delay);

You define getTime as expecting a parameter but did not pass one, instead you will want do to:

setInterval(function(){ getTime(el); }, wait);

Finally el.innerHTML(counter); should be el.innerHTML = counter; .

Working Fiddle here

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