Code in the JsFiddle is not working [duplicate]

2019-01-20 13:14发布

This question already has an answer here:

I have one query, for that I wanted to prepare a JSFiddle. But it's not working for a small click program. Which has just two lines of code.

HTML

<body>
    <button onclick="javascript:launchdialog();">Click Me</button>
</body>

JavaScript

function launchdialog() {
    alert('test');
}

I didn't find anything wrong in just two lines of code. Please have a look at this JSFiddle - http://jsfiddle.net/g47qqzra/

4条回答
对你真心纯属浪费
2楼-- · 2019-01-20 13:29

You can set the option to No wrap in head or body.

When you use onload or onDomReady, your code is wrapped inside another function that is invoked on load or ready event. So, your function is not accessible from outside of that function. And you'll get error

ReferenceError: functionName is not defined

Making the function no wrap makes it global, can be accessed from anywhere.

Updated fiddle

Jsfiddle Doc

查看更多
smile是对你的礼貌
3楼-- · 2019-01-20 13:33

On the left set "No wrap - in <head>"

Here is the updated JSFiddle link

查看更多
\"骚年 ilove
4楼-- · 2019-01-20 13:47

onLoad:

  • This means wrap the code so it will run in onLoad window event. This runs when the entire page has loaded (such as images).

onDomReady:

  • This means to wrap the code so it will run in onDomReady window event. This runs when the DOM has loaded.

no wrap - in <head>:

  • This will place your JavaScript code in the <head> section

no wrap - in <body>:

  • This will place your JavaScript code in the <body> section

I would like to note that more information can be found in jsFiddle's documentation.

Your working Fiddle

查看更多
一纸荒年 Trace。
5楼-- · 2019-01-20 13:48

This is because you script is not loaded and the function launchdialog() is not found when the page is loaded. If you place the script in head tag, it will be loaded before the page is loaded, hence solve your issue. When you use 'onLoad' option script is loaded only after the document is loaded i.e. in the end. Just select "No wrap - in " on the left set

查看更多
登录 后发表回答