javascript onclick
世界只因有你
世界只因有你 2017-05-19 10:20:56
0
3
586

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()

世界只因有你
世界只因有你

reply all(3)
漂亮男人

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

PHPzhong

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template