标头中的JavaScript代码 [英] JavaScript code place in the header

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

问题描述

我不清楚将其添加到标头部分时,为什么它无法正常运行javascript代码.

I am not clear why its not working the javascript code when I add it to the header section as follows.

我们可以按如下方式在体内放置一个javascript代码

We can place a javascript code within the body as follows

<html> 

 <head>
    <title> Simple Test </title>    
 </head>
 <body>
        <div id="mydiv"> This is the div content </div>

        <script type="text/javascript" >
           document.getElementById("mydiv").innerHTML=Date();         
        </script>   

 </body>
</html>

但是,当我将相同的JavaScript代码放在标头部分中时,它是行不通的.

But when I place the same JavaScript code in the header section it doesn't work.

<html>
  <head>
   <title> Simple Test </title>

   <script type="text/javascript" >
      document.getElementById("mydiv").innerHTML=Date();         
   </script>    

  </head>

有人可以解释这个问题吗?我知道我可以在标头中编写JavaScript函数并在事件中调用它.但是我们不能以这种方式使用.如果不能为什么.

Can Someone please explain the issue. I know I can Write a JavaScript function in header and call it in an event. But can't we Use in this way. If Can't why.

推荐答案

因为加载页面时,当浏览器到达该< script> 元素时,#mydiv元素具有尚未创建.

because when the page is loaded, by the time the browser gets to that <script> element, the #mydiv element has not yet been created.

要么使用"onload"事件,要么将脚本放在页面底部.

either use an "onload" event, or put your scripts at the bottom of the page.

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

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