我不清楚将其添加到标头部分时,为什么它无法正常运行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代码
发布评论