1、报错的代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>标题</title>
<style type="text/css"> </style>
<script type="text/javascript">
var btn = document.getElementById("btn");
btn.onclick = function () {
alert("触发了点击事件");
};
var btn1 = document.getElementById("btn1");
var btn2 = document.getElementById("btn2");
btn1.onclick = function () {
document.getElementById("t2").value = document.getElementById("t1").value
};
btn2.onclick = function () {
document.getElementById("t2").value = ""
}
</script>
</head>
<body>
<button id="btn">我是按钮</button>
<br><br>
<input id="t1" type="text" value="文本1">
<input id="t2" type="text">
<button id="btn1">copy</button>
<button id="btn2">取消</button>
</body>
</html>
2:报错的原因
文档的加载过程是自上向下加载。使用未命名的变量、会报错
3、解决办法
1、将Javascript代码从<head> 标签中放入<body> 中 2、如果非要将该段代码放入到head标签中该怎样做???
修改后的代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>标题</title>
<style type="text/css"> </style>
<script type="text/javascript">
window.onload = function(){
var btn = document.getElementById("btn");
btn.onclick = function () {
alert("触发了点击事件");
};
var btn1 = document.getElementById("btn1");
var btn2 = document.getElementById("btn2");
btn1.onclick = function () {
document.getElementById("t2").value = document.getElementById("t1").value
};
btn2.onclick = function () {
document.getElementById("t2").value = ""
}
}
</script>
</head>
<body>
<button id="btn">我是按钮</button>
<br><br>
<input id="t1" type="text" value="文本1">
<input id="t2" type="text">
<button id="btn1">copy</button>
<button id="btn2">取消</button>
</body>
</html>
|