最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

events - JavaScript - addEventListener "click" doesn't work - Stack Overflow

programmeradmin1浏览0评论

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>

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.

Share Improve this question edited May 31, 2017 at 13:25 Milan Chheda 8,2493 gold badges22 silver badges35 bronze badges asked May 31, 2017 at 12:10 Mateusz KawkaMateusz Kawka 4221 gold badge4 silver badges16 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 6

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>

Try this:

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

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

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

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>

发布评论

评论列表(0)

  1. 暂无评论