问题
I'm trying to change the color in a text box from blue to red on click, however, it's always red, the event listeners not working for some reason.
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>
回答1:
When you call addEventListener
, you need to pass a function as the second parameter. But if you think about it, you're actually passing the return value of a function call. Quite different!
button1.addEventListener("click", changeColor);
is the correct usage. You're telling the event listener which function to call when an event comes in. It'll call the event handler for you. Think of your function as just any other variable you would pass into a function.
回答2:
There are 2 mistakes in your code:
button1.addEventListener("click", changeColor());
You cannot directly call function when attaching event listener. You need to attach the functionchangeColor
- You need to call the function
formFun
at the time of script loading so the the event gets binded to the dom elements
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>
回答3:
What you immediately need to do first is call the function formFun() and also do the below:
Correct this line of code: button1.addEventListener("click", changeColor());
to
button1.addEventListener("click", changeColor);
You are registering a listener here, so you specify the function name only like changeColor, and not changeColor() which will actually call the function.
Hope that help!
来源:https://stackoverflow.com/questions/45774313/adding-a-click-event-listener-in-script-not-working