问题
I am trying to get myself started with jsFiddle. So I tried to run a simple code snippet which includes all HTML, CSS and JavaScript code.
Javascript does not works If I select onLoad in Frameworks & Extensions dropdown
But it does work when I select No Wrap - in from the dropdown
Can you tell me what that means . I have already read this question on SO JavaScript not running on jsfiddle.net
But not able to understand the solution mentioned there.
回答1:
When you select onLoad, your JavaScript is wrapped with an onload function. This means your code will run when the page has finished loading, but is no longer available in the global scope. It looks like this
window.onload=function(){
function myFunction() {
alert("Hello");
}
}
A workaround might be to assign variables to the window
object so that they are accessible anywhere in the page.
For example:
function myFunction() {
alert("Hello");
}
window.myFunction = myFunction;
and
<button onclick="window.myFunction()" >Hi</button>
回答2:
When using onLoad
, the function won't become global one, so you can't invoke it directy from HTML. If it is global - like when using no-wrap - it works.
The onLoad
generates something similar:
window.onload = function () {
function myFunction() {
}
}
So, myFunction()
is only visible directly in the closure of the anonymous function.
来源:https://stackoverflow.com/questions/32206369/jsfiddle-onload-and-no-wrap-in-body