javascript - Can't make the content of the timer update every second
问题描述
In this code, I create a div element and append it to 'timer' div. I would like to primarily clear the div element to display seconds value every second. However, I get seconds only ONE time. I don't understand how to fix it. I added a check to get rid of child elements of timer(if they exist which of course will happen when many elements will be created). How to make the content of the timer div update every second?
let timer = document.getElementById('timer');
let time = setInterval(() => {
while (timer.firstChild) {
timer.removeChild(timer.firstChild);
}
timer.append(document.createElement('div').textContent = `${new Date().getSeconds()}`)
}, 1000);
解决方案
您的代码似乎正在运行,请尝试此代码段。
let timer = document.getElementById('timer');
let time = setInterval(() => {
while (timer.firstChild) {
timer.removeChild(timer.firstChild);
}
timer.append(
document.createElement('div').textContent = `
${new Date().getSeconds()}
`)
}, 1000);
<div id="timer"></div>
推荐阅读
- flutter - 使用 BottomNavigation Flutter 从嵌套路由内部修改 FAB
- ios - 为什么 UITextField 在输入字符串的末尾添加空格?
- google-cloud-platform - 如果 HTTP 请求被取消,云函数会完成吗?
- wordpress - WP Bakery woocommerce 展示产品子类别(免费)
- laravel - 如何删除 url 中的 pages 单词 - laravel 5.6 中的 domain/pages/disability-support
- openssl - 将 .crt 转换为 .pem 文件时出错
- java - 如何在 JAVA 中捕获 UDP 数据包?
- sql - 显示支付总费用 RS.50000 及以上的客人详细信息。编写查询以获取客人 ID、客人姓名和总费用总和
- c# - 用等效的枚举值自动替换数字常量?
- azure - 是否可以将上传的图片用于 OCR 分析存储在 azure 存储中以供以后调试和分析?