开发者

why are variables declared outside a function null?

开发者 https://www.devze.com 2023-01-30 09:45 出处:网络
i made this using mootools: $(\"fox\").addEvent(\"click\", function(){ alert(\"clicked\"); }); and the html:

i made this using mootools:

$("fox").addEvent("click", function(){
alert("clicked");
});

and the html:

<p id="fox">A</p>

now if i try it here http://jsfiddle.net/5uJ54/3/ , it works but if i try it in a browser and thats all the code it doesnt, i get 开发者_JAVA百科this in firebug:

$("fox") is null

and it doesnt work in chrome either.

why is this happening? i have also tried putting everything inside a function but it still doesnt work.


If you try to select your element before the document is ready then you will get null.

The JSFiddle sandbox you have is setup to run after the document has been loaded.

To get the code to work in your document you can listen for this MooTools event which will be triggered after the document is ready: http://mootools.net/docs/core/Utilities/DOMReady

Your example would end up looking something like this:

window.addEvent('domready', function() {
    $("fox").addEvent("click", function(){
        alert("clicked");
    });
});


Are you sure mootools is being loaded and you are putting the javascript within some sort of domready event? (Not sure what mootools's version of it is).


Because you didn't include the mootools javascript library anywhere?

0

精彩评论

暂无评论...
验证码 换一张
取 消