简体   繁体   中英

JavaScript onclick event is not working

A simple JavaScript onclick event is not working but I don't understand why, here is the code:

<button onclick="removeLol()">remove style</button>

function removeLol() {
    alert("hello");
}

and here is a simple example: http://jsfiddle.net/YNQg6/1/

That's only because of the way how jsfiddle inserts the javascript.

Jsfiddle wraps your code into a function which limits the scope and protects the global namespace:

window.onload=function(){
  function removeLol() {
    alert("hello");
    element.className = element.className.replace(" lol ", "");
  }
}

If you tell jsfiddle to inject the code into the document body it works:

http://jsfiddle.net/YNQg6/13/

Or you could turn your "local" function in a global one:

window.removeLol = removeLol;

The code works just fine (just tried it on my server). Check your console for other errors that may be causing the script to not run

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