我用了定时器 和清除定时器没有实现啊3-13编程练习为什么实现不了啊
来源:3-12 箭头函数的应用
球球不一般
2021-12-21 20:16:02
<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')
var show = {
content: "Hello World",
timer: null,
start: function () {
setInterval(function () {
box.innerHTML = this.content
co
}, 1000)
},
stop: function () {
box.onclick = function () {
clearInterval(this.timer)
}
},
}
show.start()
show.stop()
</script>
搜索
复制
2回答
好帮手慕久久
2021-12-22
同学你好,“烟雨平生_Elisha”的说法是正确的,具体如下:
1、要将定时器赋值给timer,这样this.timer才会有值:

2、box.innerHTML中的内容,要保留之前的内容,再拼接上新的“Hello World”,所以要用+=:

这里可以不使用`${this.content} `这种写法。
3、定时器中的函数,要写成箭头函数,这样是为了让this指向对象show:

4、停止操作,需要将点击事件绑定在stopBtn上,事件处理函数也要使用箭头函数:

另外,开启定时器的操作也要添加到开始按钮的点击事件中:

代码如下:
const startBtn = document.getElementById('start')
const stopBtn = document.getElementById('stop')
const box = document.getElementById('box')
var show = {
content: "Hello World",
timer: null,
start: function () {
startBtn.onclick = () => {
// this.timer=setInterval(function () {
this.timer = setInterval(() => {
box.innerHTML += this.content
// co
}, 1000)
}
},
stop: function () {
// box.onclick = function () {
stopBtn.onclick = () => {
clearInterval(this.timer)
}
},
}
show.start()
show.stop()
祝学习愉快!
Elisha666
2021-12-21
你timer没赋值给定时器,还有box.innerHTML = this.content写得不对,可以用模板字符串解决,可以参考一下我的
<!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')
var show = {
content: "Hello World",
timer: null,
start: function () {
// 在此补充代码
startBtn.onclick = () => {
this.timer = setInterval(() => {
box.innerHTML += `${this.content} `;
}, 1000);
};
},
stop: function () {
// 在此补充代码
stopBtn.onclick = () => {
clearInterval(this.timer);
};
},
}
// 在此补充代码
show.start();
show.stop();
</script>
</body>
</html>相似问题