大家!
我开发了简单的脚本并面临下一个问题:我尝试在回调函数内重新分配 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/