JavaScript - addEventListener“click”不起作用

时间:2017-05-31 12:10:03

标签: javascript events dom addeventlistener

我希望在点击按钮后从输入中获取一个值但是所有时间功能

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()已在加载页面上启动。求你帮帮我。

3 个答案:

答案 0 :(得分:4)

当你这样做时:

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

您将console.log(...)的返回值传递给addEventListener。该值为undefined

你想要的是将它包装成一个函数:

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>

答案 1 :(得分:1)

试试这个:

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

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

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

答案 2 :(得分:0)

为什么不在html中实现点击按钮?像这样:

&#13;
&#13;
function getInput() {
console.log(document.querySelector("#inputSector").value);  
}
&#13;
<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>
&#13;
&#13;
&#13;