Why isn't the javascript onclick function call

2019-09-09 06:03发布

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

6条回答
该账号已被封号
2楼-- · 2019-09-09 06:09

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

查看更多
Melony?
3楼-- · 2019-09-09 06:13

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

DEMO

function doSomething() {
  alert('Hello!'); 
}
查看更多
神经病院院长
4楼-- · 2019-09-09 06:19

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");
});
查看更多
SAY GOODBYE
5楼-- · 2019-09-09 06:19

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.

查看更多
萌系小妹纸
6楼-- · 2019-09-09 06:22

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

查看更多
叼着烟拽天下
7楼-- · 2019-09-09 06:30

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>
查看更多
登录 后发表回答