javascript 代码在 HEAD 标签中不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15675745/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript code not work in HEAD tag
提问by AminM
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>
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 不存在,但我只想将我的 JavaScript 代码放在<head>
标签中,而不会将它放在 HTML 代码的中间。
But this code only works when I put the <script>
tag after the <div>
tag.
I use VS2010 and firefox 19.0.1
但是此代码仅在我将<script>
标签放在标签后时才有效<div>
。我使用 VS2010 和 firefox 19.0.1
Is there anyway to put code in <head>
tag?
反正有没有把代码放在<head>
标签中?
回答by Tharsan
Your script relies on the DOM being ready, so you need to execute that function call only after the DOM is ready.
您的脚本依赖于 DOM 准备就绪,因此您只需要在 DOM 准备就绪后执行该函数调用。
<script language="javascript" type="text/javascript">
window.onload = function() {
document.getElementById("msg1").innerHTML = document.URL.toString();
}
</script>
回答by Abbas Rahimi
Your script uses a DOM element and therefore must run after the DOM is loaded. You can do that by using this function:
您的脚本使用 DOM 元素,因此必须在加载 DOM 后运行。你可以使用这个函数来做到这一点:
$(document).ready(function(){
//code here
}
回答by Michael Geary
The various tags in your HTML page are loaded and processed in the order in which they appear on the page. Your <script>
tag is executed immediately when it is parsed in the <head>
. This is before the <body>
and the elements inside the <body>
are parsed. So, the script tries to reference an element that is not defined at the time it is executed.
HTML 页面中的各种标签按照它们在页面上的显示顺序加载和处理。您的<script>
标记在<head>
. 这是在解析<body>
和 里面的元素之前<body>
。因此,脚本尝试引用在执行时未定义的元素。
回答by Valentin Vasilyev
Michael Geary is right, in order to execute your code, I'd use jQuery library (a de-facto standard in JS development) and utilize the DOM ready event. This will ensure the code in the handler will execute once DOM is fully loaded.
Michael Geary 是对的,为了执行您的代码,我将使用 jQuery 库(JS 开发中的事实上的标准)并利用 DOM 就绪事件。这将确保处理程序中的代码将在 DOM 完全加载后执行。
<script>
$(function(){
$('#msg1').html(document.URL.toString());
});
</script>
回答by Valentin Vasilyev
Your script uses dom element and must run after the dom loaded.
您的脚本使用 dom 元素并且必须在 dom 加载后运行。
Wrap your code in a function and call it after dom loaded
将您的代码包装在一个函数中并在 dom 加载后调用它
function myfunc(){
//code here
}
window.onload = myfunc();