JavaScript代码在HEAD标记中不起作用 [英] javascript code not work in HEAD tag

查看:115
本文介绍了JavaScript代码在HEAD标记中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的网页有以下代码:

My webpage has the following code:

<html>
<head>
    <title>This is test Page</title>

     <script language="javascript" type="text/javascript">

         document.getElementById("msg1").innerHTML = document.URL.toString();
        </script>

</head>
<body>

    <div class="sss">
        <p id="msg1"></p>
    </div>


</body>
</html>

正如你现在在脚本执行div时不存在但我想把我的仅限JavaScript代码在< head> 标记中,我不会将它放在HTML代码的中间。

As you now at the time the script executes the div doesn't exist but I want to put my JavaScript code only In the <head> tag and I won't put it in middle of HTML code.

但是,只有在< div> 标签之后放置< script> 标签时,此代码才有效。
我使用VS2010和firefox 19.0.1

But this code only works when I put the <script> tag after the <div> tag. I use VS2010 and firefox 19.0.1

有没有把代码放在< head> 标记?

Is there anyway to put code in <head> tag?

推荐答案

您的脚本依赖于DOM准备就绪,所以您只需在DOM之后执行该函数调用准备好。

Your script relies on the DOM being ready, so you need to execute that function call only after the DOM is ready.

<script language="javascript" type="text/javascript">

window.onload = function() {
    document.getElementById("msg1").innerHTML = document.URL.toString();
}

</script>

这篇关于JavaScript代码在HEAD标记中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆