开发者

JS Prototype screwing around with me

    <link rel="stylesheet" type="text/css" media="screen" href="style.css"/>
    <script type="text/javascript" src="prototype.js"></script>
    <script type="text/javascript">
        $('lol').update('Hi!');
    </script>

    <title>Memory Game</title>
</head>
<body>
    <h1 id="lol">Hello</h1>

</body>


Simple enough. Nothing happens and this is what FF gives me in the console:

$("l开发者_如何学编程ol") is null [Break On Errors] $('lol').update('Hi!'); index.html (row 10)

What am I missing?


Scripts run immediately as the script element is parsed. Since the script element appears before lol, it can't find it.

Either move the script to the end of the document, or delay execution someone (e.g. by wrapping it in a function and attaching that to the onload event).


I think you should add a # if you are accessing by id:

$('#lol').update('Hi!');

EDIT: Sorry, I thought you were using jQuery. You need to put the

<script type="text/javascript">
    $('lol').update('Hi!');
</script>

At the bottom of the page.


window.load = function() { $('lol').update('Hi!'); })


Try the cross-browser compatible on DOM load method, this fires when the document is loaded but before the page is drawn:

<script>
document.observe("dom:loaded", function() {
  $('lol').update('Hi!');
});
</script>

You can also put simple script tags rather than text/whateverscript.


Maybe your missing a document ready check:

document.observe("dom:loaded", function() {
  $('lol').update('Hi!');
});

jsFiddle example here: http://jsfiddle.net/qWzTp/1/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜