无法在 javascript 回调中写入 textContent 属性

Can't write to textContent property inside javascript callback

各位!

我开发了简单的脚本并面临下一个问题:我尝试在回调函数中重新分配 element.innerText 属性,但没有任何反应。


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JS Countdown</title>
</head>
<body>
    <span class="countdown">00:01:00</span>
    <span class="test">AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA!!!!!!!!!!!!!!!!!</span>
    <script>

        let counter = 134; // number of seconds
        let countdown =  document.querySelector('.countdown'); // where time content located


        // timer function 
        // duration of timer
        // countdown = element where put content
        !function timer(duration, countdown) {

            // run loop
            let id = setInterval(function () {
                if( duration === 0 ) {
                    clearInterval(id);
                    console.log("Timer with id #" + id +  " stopped!");

                    // when loop ends I want to paste some text into tag
                    // but nothing happen
                    countdown.textContent = "Loop ends!"; 
                }

                countdown.innerText = duration--; // this works fine and content of tag updates on 
                // every loop

            }, 10);
        }(counter,countdown); // run



    </script>
</body>
</html>

那么,如何通过 setInterval 回调更改外部标签的值?

在写完文本后放一个return,否则你的代码将继续进行并覆盖文本值。

<script>

    let counter = 134; // number of seconds
    let countdown =  document.querySelector('.countdown'); // where time content located


    // timer function 
    // duration of timer
    // countdown = element where put content
    !function timer(duration, countdown) {

        // run loop
        let id = setInterval(function () {
            if( duration === 0 ) {
                clearInterval(id);
                console.log("Timer with id #" + id +  " stopped!");

                // when loop ends I want to paste some text into tag
                // but nothing happen
                countdown.textContent = "Loop ends!"; 
                return;
            }

            countdown.innerText = duration--; // this works fine and content of tag updates on 
            // every loop

        }, 10);
    }(counter,countdown); // run



</script>

看起来你希望循环在打印出 "loop ends" 后结束,但使用当前代码它将继续,你可以通过在 if 末尾添加 'return;' 来结束循环声明。