I encountered such a problem when writing JS today:
function init() {
var btn = document.getElementById('sort-btn');
btn.onclick = btnHandle();
}
The above is my JS code part. Pay attention here, the second sentence in the init function, btn.onclick = btnHandle();
My original intention is to click the button and execute the btnHandle function, but the actual situation is to refresh After the page, the btnHandle function is executed directly.
Then I changed the code to this
function init() {
var btn = document.getElementById('sort-btn');
btn.onclick = btnHandle;
}
After removing the () in the btn.onclick = btnHandle(); statement, the code runs normally as I thought.
why is that? btnHandle and btnHandle()
btn.onclick
接受一个函数,代表当 btn 被点击的时候执行这个函数,而你的btnHandle()
代表了执行这个函数,给btn.onclick
is its return value, of course it is executed first.The following writing means that when
btn.onclick
时,执行btnHandle
is a function.btn.onclick = btnHandle(); This code means to assign the execution result to the click event
It means that when you refresh the page, the init function will be executed. After the init function is executed, when onclick is bound,
This line of code btn.onclick = btnHandle();
is equivalent to executing the btnHandle method and assigning the return value of the method to btn. .onclick.
And btn.onclick = btnHandle;
is equivalent to btn.onclick = function(){xxxxx};
That is to say, the reference of the btnHandle variable is assigned to btn.onclick
So when the click event is triggered, the btnHandle representative will be executed. Function methods