问题
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