gpt4 book ai didi

javascript 手动计时器 - 脚本给出错误 : (TypeError: Cannot read property 'value' of null)

转载 作者:行者123 更新时间:2023-11-27 22:32:03 24 4
gpt4 key购买 nike

我不明白为什么它没有取值,它给出类型错误不能在控制台日志中取空值

var seconds = parseInt(document.getElementById('secs').innerHTML);
var timer;

function countdown() {
var container = document.getElementById('dl');
seconds--;
if (seconds > 0) {
container.innerHTML = 'Please wait <b>' + seconds + '</b> seconds..';
} else {
container.innerHTML = 'Time over';
clearInterval(timer);
}
}
<!-- <div id="dl"></div>
<input type="button" onclick="setInterval(countdown, 1000);" id="dl" value="Start" /> -->

<input type="text" id="secs" placeholder="enter seconds" />
<input type="button" onclick="setInterval(countdown, 1000);" id="dl" value="Start" />
<div id="dl"></div>

最佳答案

一些事情:

  1. input 元素没有有用的 innerHTML,它们有 value

  2. 您尝试在脚本运行时立即读取输入。您希望等到用户单击按钮。

  3. 您永远不会将间隔的句柄保存到计时器

  4. 您有两个 id 为“dl”的元素。文档中只能有一个具有给定id的元素。

请参阅下面的评论,了解每个更正的地方:

// #1: Wait for user to click the button before reading the value
// Note we're using modern event handling, rather than onxyx attributes
document.getElementById("dl").addEventListener("click", function() {
// #2: Use `value`, not `innerHTML`, with `input` elements
var seconds = parseInt(document.getElementById('secs').value);
// #3: Save the interval's handle to `timer`
var timer = setInterval(countdown, 1000);

function countdown() {
var container = document.getElementById('count');
seconds--;
if (seconds > 0) {
container.innerHTML = 'Please wait <b>' + seconds + '</b> seconds..';
} else {
container.innerHTML = 'Time over';
clearInterval(timer);
}
}
}, false);
<input type="text" id="secs" placeholder="enter seconds" />
<input type="button" id="dl" value="Start" />
<!-- #4: Use a different ID for the timer output -->
<div id="count"></div>

<小时/>

您还可以考虑在用户单击时立即显示一条消息,而不是等待第一秒。我将把它作为练习留给读者......

关于javascript 手动计时器 - 脚本给出错误 : (TypeError: Cannot read property 'value' of null),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39483699/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com