javascript - 无法写入 javascript 回调中的 textContent 属性

标签 javascript closures innertext

大家!

我开发了简单的脚本并面临下一个问题:我尝试在回调函数内重新分配 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 回调更改外部标记的值?

最佳答案

在写入文本后添加一个回车符,否则您的代码将继续执行并覆盖文本值。

<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>

关于javascript - 无法写入 javascript 回调中的 textContent 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57749328/

相关文章:

vba - 优化Vba代码

javascript - 使用 javascript、jquery 插件上传多个文件

javascript - 输入文本框不能用 jQuery Draggable 编辑?

javascript - 下拉列表问题 ZURB 基金会

javascript - 根据数组的大小填充 JS 对象

rust - 如何从Rust语言的函数返回闭包? [复制]

jquery - 在 JQuery 中添加超链接到文本

javascript - 使用绑定(bind)、调用和应用方法设置超时

javascript - 从闭包中取回数据