发布时间:2023-07-21 18:30
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>标题</title>
<style type="text/css"> </style>
<script type="text/javascript">
//获取button对象
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>
文档的加载过程是自上向下加载。使用未命名的变量、会报错
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(){
//获取button对象
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>