本文介绍了JavaScript-addEventListener"click"不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在单击按钮后从输入中获取一个值,但需要所有时间功能

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()在加载页面上启动.请帮帮我.

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

推荐答案

当您这样做:

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

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

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>

这篇关于JavaScript-addEventListener"click"不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 02:44