为什么赢了';我的换行符不会在JavaScript中变为非活动状态吗?
我尝试使用JavaScript在加载页面时关闭为什么赢了';我的换行符不会在JavaScript中变为非活动状态吗?,javascript,html,line-breaks,Javascript,Html,Line Breaks,我尝试使用JavaScript在加载页面时关闭标记的效果,但由于某些原因,它无法工作。我觉得我犯了一些错误,下面是我的html: <HTML> <HEAD> <SCRIPT type="text/javascript"> var brTag = document.getElementById('newline'); brTag.style.display = 'none'; </SCRIPT> </HEAD> <BODY&
标记的效果,但由于某些原因,它无法工作。我觉得我犯了一些错误,下面是我的html:
<HTML>
<HEAD>
<SCRIPT type="text/javascript">
var brTag = document.getElementById('newline');
brTag.style.display = 'none';
</SCRIPT>
</HEAD>
<BODY>
Line 1 <BR id = "newline" />
Line 2
</BODY>
</HTML>
var brTag=document.getElementById('newline');
brTag.style.display='none';
第1行
在声明新行之前,您正在引用它。创建元素后尝试运行脚本(即,在文件的后面,或在文件后面调用的函数中)我们尊敬的同事说的是:
<html>
<head>
<script type="text/javascript">
window.onload = function () {
var brTag = document.getElementById('newline');
brTag.style.display = 'none';
};
</script>
</head>
<body>
Line 1 <br id="newline" />
Line 2
</body>
</html>
window.onload=函数(){
var brTag=document.getElementById('newline');
brTag.style.display='none';
};
第1行
或者这个:
<html>
<head>
</head>
<body>
Line 1 <br id="newline" />
Line 2
<script type="text/javascript">
var brTag = document.getElementById('newline');
brTag.style.display = 'none';
</script>
</body>
</html>
第1行
这样执行代码时,DOM中就存在
。现在,您是在将
添加到DOM树之前执行代码的。此时document.getElementById('newline')当执行code>时,元素还不存在,因此它返回null
。您应该得到一个JavaScript错误(无法读取null的属性'style'。如果您在元素存在时执行它,它可以正常工作:您知道在HTML文档中,“
”中的“/”只是垃圾吗?我实际上不知道,我知道您不需要使用
关闭它,但我不知道。第二种解决方案很好,但没有window.onready处理程序。你想要窗口。加载。你是对的(不知道我在想什么…)。更新答案。