Why isn't the javascript onclick function called?

非 Y 不嫁゛ 提交于 2019-12-11 18:45:39

问题


I have created a JSFiddle to describe the issue. Why isn't the alert displayed when I call the doSomething() function?


回答1:


You need to disable framework option in jsfiddle for javascript to work

DEMO

function doSomething() {
  alert('Hello!'); 
}



回答2:


This is because doSomething() function is not defined in the HTML page. In jsfiddle your function (in js pane) is wrapped by document onload event of jquery. (see at the left side of jsfiddle for settings). So Its executed like this,

$(document).ready(function() {
    function doSomething() {
      alert('Hello!'); 
    }
});

See how its wrapped. Its not accessible. To fix it you should assign it to window object. In the js pane write the function as

window.doSomething=function() {
  alert('Hello!'); 
}

It'll work


Its recommended you do not use onclick attributes of an HTML elements. Its better to assign event handler with JS.

$("img").click(function(){
  alert("Hello");
});



回答3:


This is a "fiddle-thing". Pick nowrap (head) from the first selection in the "Choose Framework" field.




回答4:


What JsFiddle does for you is creating the <HTML>, <head> and <body> tags for you. You shouldn't include them in your HTML, because that would make the markup invalid after JsFiddle processed it. It also wraps your JS in the document's onload event. So your function was not defined in the root scope as you thought, but in th scope of the document.onload function, and you couldn't reach it from within the body, because that is outside of that function. I changed the JsFiddle attribute 'wrap in' to 'no wrap (head)' and it worked.




回答5:


Your function dosomeThing() is not defined in the page just replace header tag with this one

 <head>
    <script>
      function doSomething() {
  alert('Hello!'); 
}
    </script>
  </head>

and then try again




回答6:


Here is your complete code. just copy and paste your editor. it is

<!doctype html>
<html lang='en'>
<head>
<meta charset='utf-8'>
<title>Javascript Events</title>
<script type='text/javascript'>
window.onload = function() {
    var image_one = document.getElementById('imageOne');
    var image_two = document.getElementById('imageTwo');

    image_one.onclick = function() {
        alert('Hello!');
    }


    image_two.onclick = function() {
        alert('Hello!');
    }


}
</script>
</head>
<body>
    <img id="imageOne" src="http://upload.wikimedia.org/wikipedia/commons/thumb/0/0c/White_and_yellow_flower.JPG/320px-White_and_yellow_flower.JPG" />
    <img id="imageTwo" src="http://upload.wikimedia.org/wikipedia/en/7/70/Example.png" /> 
</body>
</html>


来源:https://stackoverflow.com/questions/14273661/why-isnt-the-javascript-onclick-function-called

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