Mouse Events on JsFiddle not working?

2019-02-28 14:54发布

I've got my fiddle here, but I can't understand why it's not calling my function on the 'onmouseout' event. http://jsfiddle.net/foreyez/Xf6LW/

any ideas?

5条回答
相关推荐>>
2楼-- · 2019-02-28 14:58

make myFunc as a global function;

I searched my code using firebug and got following generated code.

window.addEvent('load', function() {
    //window.myFunc makes myFunc as a global function
    // It can be accessed from any were inside current window.
   window.myFunc = function myFunc(x)
   {
        alert('yo');
   }
    // function below is not available gloably.
    function myFunct1(){
        alert('yo1');
    }
});

see jsfiddle

查看更多
forever°为你锁心
3楼-- · 2019-02-28 15:01

Works fine, you just needed to put the function in the head (or body after the element is in the DOM) of the document.

jsFiddle example

查看更多
放荡不羁爱自由
4楼-- · 2019-02-28 15:03

It's because the functions you create in the JavaScript panel are not global when you have the onLoad option selected. Your JavaScript gets wrapped in a function.

If you do want them to be global you have to either do what j08961 suggested, by changing that dropdown to say no wrap (body or head) will work

The best solution would be to not set your event handlers from HTML, that's bad practice anyway, then you're not relying on global functions or mixing HTML and JS.

<div id="myDiv">
</div>​
document.getElementById('myDiv').onmousemove = function() {
  alert('here');
}

Side note: you should have noticed the error in the console saying that myFunc is undefined or something like it.

查看更多
Luminary・发光体
5楼-- · 2019-02-28 15:13

I think it's cause for jsfiddle, it declares all the javascript AFTER the HTML. The HTML is going to run and look for a myFunc and not find it. Then it's going to load the JS and it won't even run it.

查看更多
来,给爷笑一个
6楼-- · 2019-02-28 15:24

Here you can see the changes : jsfiddle.

查看更多
登录 后发表回答