简体   繁体   中英

can't get the value of this input

I am trying to get the value of my input but it's saying mouse event. If I just call this function instead of eventListener, it's say undefined.

 let btn = document.getElementById('btn'); let pra = document.getElementById('inp1').value; let cont = document.getElementById('container') function execute(pra) { let newElemet = document.createElement('p'); newElemet.innerHTML = pra; cont.appendChild(newElemet) } btn.addEventListener('click', execute)
 <div id="container"> <input id="inp1" type="text"> <button id="btn">Add</button> </div>

Two problems.

  1. The pra argument of the event handler represents the event (a mouse event as you say) and overshadows the pra global variable. You can remove the argument to get rid of the overshadowing.

  2. The global pra variable contains the value that was there (empty) when the script is loaded. You need to make the pra representing the input element.

 let btn = document.getElementById('btn'); let pra = document.getElementById('inp1'); let cont = document.getElementById('container') function execute() { let newElemet = document.createElement('p'); newElemet.innerHTML = pra.value; cont.appendChild(newElemet) } btn.addEventListener('click', execute)
 <div id="container"> <input id="inp1" type="text"> <button id="btn">Add</button> </div>

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