Why isn't my JavaScript working in JSFiddle?

前端 未结 7 1426
萌比男神i
萌比男神i 2020-11-21 05:11

I can\'t find out what is the problem with this JSFiddle.

HTML:


Jav

7条回答
  •  青春惊慌失措
    2020-11-21 05:30

    There is another way, declare your function into a variable like this :

    test = function() {
      alert("test");
    }
    

    jsFiddle


    Details

    EDIT (based on the comments of @nnnnnn)

    @nnnnnn :

    why saying test = (without var) would fix it ?

    When you define a function like this :

    var test = function(){};
    

    The function is defined locally, but when you define your function without var :

    test = function(){};
    

    test is defined on the window object which is at the top level scope.

    why does this work?

    Like @zalun say :

    If you do not specify the wrap setting it defaults to "onLoad". This results with all JavaScript being wrapped in a function run after result has been loaded. All variables are local to this function thus unavailable in the global scope.

    But if you use this syntax :

    test = function(){};
    

    You have an access to the function test because it's defined globally


    References :

    • https://stackoverflow.com/a/338053/3083093
    • https://stackoverflow.com/a/5830423/3083093

提交回复
热议问题