简体   繁体   中英

Pressing button - call function in JS

Referring to question posted (link below) before 7 months,

Javascript. Pressing button - call function

I would like to ask why I am getting those 2 errors when executing the code on the compiler of the university. Please note that I have zero control on the code of the html which the compiler react with

Uncaught: TypeError: Cannot set property 'onclick' of null

Uncaught: ReferenceError: createdButton is not defined

function greet() {
    console.log('Hi there')
  }

  function addButton() {
    const button = document.createElement('button')
    const buttonTextNode = document.createTextNode('Click')
    button.appendChild(buttonTextNode)
    button.onclick = greet
    document.body.appendChild(button)
  }

  const buttonCreator = document.getElementById('btn')
  buttonCreator.onclick = addButton

These errors are pretty straightforward. The first one is telling you that there is no element with the id of btn in your HTML, hence why it's returning null.

For the second one I don't see where you're calling createdButton , but it's telling you it isn't defined anywhere. If I had to take a guess, either you're calling createdButton before you define it or there's not a variable named createdButton .

Try:

  1. You have no element with id of "btn", try adding the id to the button you want to listen the onclick event.

  2. I wonder why this error is happening: Uncaught: ReferenceError: createdButton is not defined . Because, there are no words about createdButton . Can you give us the full code?

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