JavaScript - addEventListener “click” doesn't work

╄→尐↘猪︶ㄣ 提交于 2021-01-01 08:07:46

问题


I want take a value from input after click on button but all the time function

var buttonToBinary = document.querySelector("#toBinary");
buttonToBinary.addEventListener('click', console.log(getInput()));

function getInput() {
  return document.querySelector("#inputSector").value;
}
<input type="text" name="userInput" id="inputSector" value="aa" />
<button id="toBinary" type="submit">to binary</button>

getInput() was started on load page. Please, help me.


回答1:


When you do:

buttonToBinary.addEventListener('click', console.log(getInput()));

You are passing the returned value of console.log(...) to addEventListener. That value is undefined.

What you want, instead is to wrap that into a function:

var buttonToBinary = document.querySelector("#toBinary");
buttonToBinary.addEventListener('click', function() {
  console.log(getInput())
});

function getInput() {
  return document.querySelector("#inputSector").value;
}
<input type="text" name="userInput" id="inputSector" value="aa" />
<button id="toBinary" type="submit">to binary</button>



回答2:


Try this:

var buttonToBinary = document.querySelector("#toBinary");

function getInput() {
    return document.querySelector("#inputSector").value;
}

buttonToBinary.addEventListener('click', function(){
    console.log(getInput());
});



回答3:


Why not implement click on button in html? Like this:

function getInput() {
console.log(document.querySelector("#inputSector").value);  
}
<html>

  <head>
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
  </head>

  <body>
    <input type="text" name="userInput" id="inputSector" value="aa" />
    <button onclick="getInput()" id="toBinary" type="submit">to binary</button>
  </body>

</html>


来源:https://stackoverflow.com/questions/44284455/javascript-addeventlistener-click-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!