标头中的JavaScript代码

编程入门 行业动态 更新时间:2024-10-26 12:21:31
本文介绍了标头中的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代码

本文发布于:2023-11-09 16:01:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1572808.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:代码   标头中   JavaScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!