简体   繁体   中英

Why is this code working here but not on JSFiddle

I have this simple code which has nothing wrong with it and it runs here but not on JSFiddle. On inspecting the console I find the following error

Uncaught ReferenceError: fn is not defined

LINK TO FIDDLE

 var fn = { one: function() { alert('1') }, two: function() { alert('2') }, three: function() { alert('3') } }; 
 <button onclick='fn.one()'>1</button> <button onclick='fn.two()'>2</button> <button onclick='fn.three()'>3</button> 

This is just a JSFiddle feature. JSFiddle, by default, wraps all your code in a $(document).ready() handler. To get your JS out of the wrapper and back into the flow of the normal DOM, just select the JSFiddle option under 'Frameworks & Extensions' and change it from 'onLoad' to 'No wrap - in head' or 'No wrap - in body'

将jsfiddle中的下拉菜单从onLoad更改为No wrap-in head或No wrap-in body。

将左侧的选项从onLoad更改为no wrap (即no wrap - in <head> no wrap - in <body> ,它运行没有问题。

It's because jsfiddle sandboxes your code in a closure.

You can see that you wrote var fn (which makes a local var), just remove the var statement to make it global and you will be able to call it the way you are now.

Though, I'd advise you to use addEventListener() .

This code on jsfiddle doesnt work because this is how scope of variables works in JavaScript.

You can see that if I change only a few characters from

var fn = // the rest of code ...

to

window.fn = // the rest of code ...

Your example works "correctly" - http://jsfiddle.net/v3gsmnvq/7/

Read about scopes even here on SO: What is the scope of variables in JavaScript?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM