javascript onclick not working in jsfiddle

拥有回忆 提交于 2019-11-30 18:20:42

You need to select No library (pure JS) and No wrap - in head. Then it will work as a simple HTML with javascript page.

This will be inserted in a <script> element in the <head>:

function myclick(){
  alert("myclick")
}

See demo

As others said, for first case you have to set No wrap - in <head> or No wrap - in <body> as javascript panel settings (the blue link at js panel top-right).

For the second (your Edit) question, your code inside a function and the js will run it (within a new context), but it will do nothing as you just define a function and ignore it without any call or assignment.

if you call alert(myclick) you will see all the code is executed and its defined at that point. see this fiddle

$(document).ready(function() {

  //alert("ready is executed");

  function myclick(){
    alert("myclick is called")
    window.location.reload(true);
  }

  alert(myclick); //this will show the myclick is a defined function!

  //document.getElementsByTagName("input")[0].onclick = myclick;
})

if you call this:

document.getElementsByTagName("input")[0].onclick = myclick;

in that $(document).ready({...}) scope, it will be assigned to the button and works as you wish.

<input value="press" id='a' type="button">
document.getElementById('a').onclick = function() { alert(1); }

http://jsfiddle.net/gs6rehnx/12/

This one is working. Just remove it from document ready event. Also semicolons are optional in javascript but i advice to use them.

function myclick() {
    alert("myclick");
    window.location.reload(true);
}
<input value="press" type="button" onclick="myclick();">
<script>
    alert("home");
</script>

Here is the fiddle.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!