为什么<button>标签放在script标签前面(如下代码a),点击button后<h1>标签里面的内容可以显示时间,而放在其后面(代码b)时却不能显示?
代码a:<html>
<head> </head> <body>
<h1 id="header" ></h1>
<button id="demo" type="button" >click me</button>
<script>
document.getElementById("demo").onclick=function(){displayDate()};
function displayDate()
{
document.getElementById("header").innerHTML=Date();
}
</script>
</body></html>
代码b<html>
<head> </head> <body>
<h1 id="header" ></h1>
<script>
document.getElementById("demo").onclick=function(){displayDate()};
function displayDate()
{
document.getElementById("header").innerHTML=Date();
}
</script>
<button id="demo" type="button" >click me</button>
</body></html>
代码a:<html>
<head> </head> <body>
<h1 id="header" ></h1>
<button id="demo" type="button" >click me</button>
<script>
document.getElementById("demo").onclick=function(){displayDate()};
function displayDate()
{
document.getElementById("header").innerHTML=Date();
}
</script>
</body></html>
代码b<html>
<head> </head> <body>
<h1 id="header" ></h1>
<script>
document.getElementById("demo").onclick=function(){displayDate()};
function displayDate()
{
document.getElementById("header").innerHTML=Date();
}
</script>
<button id="demo" type="button" >click me</button>
</body></html>
解决方案 »
- 当一个页面同时有两个setInterval函数调用的冲突如何解决?
- javascript实现单击改变单元格颜色,并且获取单元格背景。
- JS 给table外面加层DIV
- html <A> href 和 onclick优先级问题,在线等,解决给分
- javascript中从输入框跳出后进行数据校验,错误情况下事件参数可以阻止跳离吗?
- JS中调用C#中数组怎么调,有问题<%=%>不能传参数呀
- 如何用返回的xml的数据来动态填充div的值?返回的数据的行数是不确定的,是不是要重写这个Div了,详见.
- table 获取单元格的对应列数
- 操作xml写法求助,谢谢!
- select下拉框有没有类似readonly的属性的?
- extjs中的url怎么用
- 正则里面的\/符号是什么含义
执行这个代码的时候 会从当前已经解析的页面中 查找 id 是 demo 的dom你的<button id="demo" 放在这个代码后面 那么页面中当然找不到这个dom1。从这个 执行中 你要能正确理解页面元素加载次序和解析 对js代码的影响
2。你以后应该从类似问题的表现来 反推原因 大胆的去理解和假设
1.把js放到外部文件中,因为首先建立dom树再连接外部文件
2.在dom准备好时再执行js,像jQuery的document.ready就是这个意思
试了一下把js放在外部文件就不会出现上述问题了,也就是说一般的话js用外连方式比较好?
试了一下把js放在外部文件就不会出现上述问题了,也就是说一般的话js用外连方式比较好?还是没理解
试了一下把js放在外部文件就不会出现上述问题了,也就是说一般的话js用外连方式比较好?还是没理解 我是说放在外面的话就会先建立好dom再执行js,就不会出现找不到"demo"这种情况了吧