简体   繁体   中英

“onclick” event gets fired automatically

I have this code that has an onclick handler and an IIFE .

var btn = document.getElementById("btn");
btn.onclick = function clickHandler(){console.log("Button clicked"); } 

//btn.onclick = function clickHandler(){console.log("Now clicked"); };

(function(){
    console.log("Hello");
})();

The issue is that the clickHandler gets invoked automatically after the page loads and the IIFE isn't invoked . However, on commenting out line 2, and un-commenting out line 3 (the commented out line in the above code), the code works as expected.

The only difference between the two lines is that the 2nd line has no ; in the end, but the 3rd line has.

Also, if I remove the IIFE and keeping the rest of the code unchanged, the code works fine.

Demo : https://codepen.io/anon/pen/Pezpqv

This is tricky. Because semicolon is missing in the second line of your code, parser doesn't stop there - and consumes all the tokens it can. In the end, the code's parsed as...

btn.onclick = function clickHandler() {
  console.log("Button clicked");
}(
  //btn.onclick = function clickHandler(){console.log("Now clicked"); };

  function() {
    console.log("Hello");
  }
)
();

See the difference () makes - your function expression is invoked immediately . It's funny that ...

function() { console.log('Hello') }

... is treated as its parameter value - which is ignored anyway.

After that, result of clickHandler is attempted to be reused as a function - but, as it returns undefined , JS stops with (intermediate value)(...) is not a function .


Thought it's a good idea to twist your code a bit - and made the following snippet to illustrate the idea with more, well, drama in it.

 const btn = document.getElementById('btn'); btn.onclick = function clickHandler(e) { console.log('Now clicked'); return e; } //btn.onclick = function clickHandler(){console.log("Now clicked"); }; (function() { console.log('Hi!'); })(); 
 <button type="button" id="btn">Click me!</button> 

Show this to your colleagues and ask the same question (why doesn't click handler work here?) if you want to make them a bit... mad. )

您在这里错过了半列

btn.onclick = function clickHandler(){console.log("Button clicked"); } ;

The problem is in starting code with ( while the previous line of code does not end with semicolon ( ; ). This treats both line of codes to be executed together like:

}(

To solve the problem either you have to put ; at the end of the statemnet or move the IIFE code to the top of your code:

 (function(){ console.log("Hello"); })(); var btn = document.getElementById("btn"); btn.onclick = function clickHandler(){console.log("Button clicked"); } 
 <button type="button" id="btn" >Click</button> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM