为什么if判断里面改不了文本内容,警告框和清除定时器都可以,求解?

let timer = null;
function countDown() {
    let n = 3;
    timer = setInterval(function () {
        n--;
        if (n === 0) {
            alert('进不来吗')
            num.textContent = 'GO';
            clearInterval(timer)
        }
        num.textContent = n;
    }, 1000)
}
countDown();

求解释一下,为什么if判断里面改不了文本内容,警告框和清除定时器都可以

阅读 2k
6 个回答

应该是因为你在 if 外面又把文本内容改了吧。

if执行完后num.textContent = n;还是会继续执行

因为 num 没有声明定义,num.textContent=xx 赋值操作无法完成。
如果 num.textContent 需要在 countDown 函数外面使用,在 let timer = null 下面添加 const num = Object.create(null) 语句即可;
如果只需要在 countDown 函数内部使用,在 let n = 3; 下面添加 const num = Object.create(null) 语句即可;
并且,此处逻辑,当 n === 0 时,num.textContent 会被覆盖成 0

if (n === 0) {
            alert('进不来吗')
            num.textContent = 'GO';
            clearInterval(timer)
        }
num.textContent = n;

修改为:

if (n === 0) {
            alert('进不来吗')
            num.textContent = 'GO';
            clearInterval(timer)
        }
else {
    num.textContent = n;
}

即可避免覆盖。

已参与了 SegmentFault 思否社区 10 周年「问答」打卡 ,欢迎正在阅读的你也加入

let timer = null;
function countDown() {
    let n = 3;
    timer = setInterval(function () {
        n--;
        if (n === 0) {
            alert('进不来吗')
            num.textContent = 'GO';
            clearInterval(timer)
            return
        }
        num.textContent = n;
    }, 1000)
}
countDown();

执行完if后,会继续执行后面的代码呢。。。

可以在浏览器调试看看。

推荐问题