老师我这样写对吗?
来源:3-13 编程练习
DB1时间的玫瑰
2021-08-19 10:29:53
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Document</title>
<style>
div {
width: 300px;
margin: 20px 0;
line-height: 30px;
background: yellowgreen;
}
</style>
</head>
<body>
<button id="start">开始</button>
<button id="stop">停止</button>
<div id="box"></div>
<script>
const startBtn = document.getElementById('start')
const stopBtn = document.getElementById('stop')
const box = document.getElementById('box')
let timer;
var show = {
content: "Hello World",
timer: null,
start: function() {
// 在此补充代码
startBtn.addEventListener('click', () => {
timer = setInterval(() => {
box.innerText += this.content;
}, 1000)
}, false);
},
stop: function() {
// 在此补充代码
stopBtn.addEventListener('click', () => {
clearInterval(timer);
}, false);
},
}
// 在此补充代码
show.start();
show.stop();
</script>
</body>
</html>
1回答
同学你好,代码问题如下:
1、timer属性在show对象中有定义,用的时候需要通过this获取,如果直接用timer相当于重新声明了变量,建议改为this.timer
2、多次点击start按钮,定时器会叠加,导致添加内容时间加快,建议在点击的时候先去掉前面的定时器
3、内容前后没有空格
建议拼接的时候手动添加空格。
参考修改:
祝学习愉快!
相似问题