Code in the JsFiddle is not working [duplicate]

不羁的心 提交于 2020-01-09 11:45:12

问题


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/


回答1:


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




回答2:


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




回答3:


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

Here is the updated JSFiddle link




回答4:


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



来源:https://stackoverflow.com/questions/31848850/code-in-the-jsfiddle-is-not-working

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