比如我的JS中有一个函数func需要在页面加载完之后点击button按钮才能调用,应该怎么办呢?请大神给一个小实例,谢谢啦
2 回答
已采纳
李晓健
TA贡献1036条经验 获得超461个赞
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>事件</title>
<script type="text/javascript">
//方法一 把事件写到window.onload里面
window.onload=function(){
var button = document.getElementById('button');
button.onclick = function(){
alert('你点击了我')
}
}
</script>
</head>
<body>
<button id="button">点击我</button>
</body>
</html><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>事件</title>
<script type="text/javascript">
function clickMe(){
alert('你点了我')
}
</script>
</head>
<body>
<!--方法二 把事件直接写到元素上-->
<button id="button" onclick="clickMe()">点击我</button>
</body>
</html><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>事件</title>
</head>
<body>
<button id="button">点击我</button>
<!--方法三 把script标签写到body标签最后-->
<script>
var button = document.getElementById('button');
button.onclick = function(){
alert('你点击了我')
}
</script>
</body>
</html>以上是不借助任何第三方工具的最常见的三种写法
添加回答
举报
0/150
提交
取消
