2017-08-19 111 views
0

我试图将文本框中的颜色从蓝色更改为红色,但是它总是红色,事件侦听器由于某种原因而不工作。在脚本不工作中添加点击事件侦听器

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>

+0

如果你可以创建一个可运行的代码,比如在jsfiddle等等 – EntryLeveDeveloper

回答

1

当你调用addEventListener,你需要通过一个函数作为第二个参数。但是如果你仔细想想,你实际上正在传递函数调用的返回值。很不一样!

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

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>

0

什么你马上需要做的第一件事就是调用函数formFun()并且还做到以下几点:

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

button1.addEventListener( “点击”,changeColor);

您正在此处注册监听器,因此您只指定函数名称,而不是changeColor,而不是changeColor(),它将实际调用该函数。

希望有所帮助!

相关问题