在脚本中添加单击事件侦听器不起作用

时间:2017-08-19 17:15:55

标签: javascript event-listener jquery-form-validator

我试图在点击时将文本框中的颜色从蓝色更改为红色,但是,它总是红色,事件监听器由于某种原因无法正常工作。

function formFun() {
  var textBox1 = document.forms[0].elements[0];
  var textBox2 = document.forms[0].elements[1];

  var button1 = document.forms[0].elements[2];
  var button2 = document.forms[0].elements[3];

  textBox2.style.backgroundColor = "blue";
  button1.style.backgroundColor = "blue";
  button2.style.backgroundColor = "blue";

  button1.addEventListener("click", changeColor());

  function changeColor() {
    textBox1.style.backgroundColor = "red";
  }

}
<form name="mForm">
  <input type="text" name="in1">
  <input type="text" name="in2">
  <button name="butt1">click1</button>
  <button name="butt2">click2</button>
</form>

3 个答案:

答案 0 :(得分:1)

当你致电addEventListener时,你需要传递一个函数作为第二个参数。但是如果你考虑一下,你实际上是在传递一个函数调用的返回值。完全不同!

button1.addEventListener("click", changeColor);是正确的用法。当事件进入时,您告诉事件监听器要调用哪个函数。它会为您调用事件处理程序。将您的函数视为您将传递给函数的任何其他变量。

答案 1 :(得分:1)

您的代码中有2个错误:

  • button1.addEventListener("click", changeColor());附加事件侦听器时无法直接调用函数。您需要附加函数changeColor
  • 您需要在脚本加载时调用函数formFun,以便事件绑定到dom元素

function formFun() {
  var textBox1 = document.forms[0].elements[0];
  var textBox2 = document.forms[0].elements[1];

  var button1 = document.forms[0].elements[2];
  var button2 = document.forms[0].elements[3];

  textBox2.style.backgroundColor = "blue";
  button1.style.backgroundColor = "blue";
  button2.style.backgroundColor = "blue";

  button1.addEventListener("click", changeColor);

  function changeColor(e) {
  console.log("change");
    e.preventDefault();
    textBox1.style.backgroundColor = "red";
    
  }

}

formFun();
<form name="mForm">
  <input type="text" name="in1">
  <input type="text" name="in2">
  <button name="butt1">click1</button>
  <button name="butt2">click2</button>
</form>

答案 2 :(得分:0)

您首先需要做的是调用函数formFun()并执行以下操作:

纠正这行代码: button1.addEventListener(“click”,changeColor());

button1.addEventListener(“click”,changeColor);

您正在此处注册一个侦听器,因此您只能像changeColor一样指定函数名,而不是实际调用该函数的changeColor()。

希望有所帮助!