jsFiddle onload and no-wrap in body

北城余情 提交于 2020-01-11 12:32:37

问题


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

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