javascript - 类不是 id 的倒数计时器
问题描述
我怎样才能使这个代码工作
<a href="downloadFile.zip" class="button">Download the file...</a>
和
var downloadButton = document.getElementsByClassName("button");
var counter = 10;
var newElement = document.createElement("p");
newElement.innerHTML = "You can download the file in 10 seconds.";
var id;
downloadButton.parentNode.replaceChild(newElement, downloadButton);
id = setInterval(function() {
counter--;
if(counter < 0) {
newElement.parentNode.replaceChild(downloadButton, newElement);
clearInterval(id);
} else {
newElement.innerHTML = "You can download the file in " + counter.toString() + " seconds.";
}
}, 1000);
我不想添加id="download"
请帮我。任何人都可以帮助我吗?拜托我需要你的帮忙。谢谢
解决方案
getElementById()
和之间的主要区别在于getElementsByClassName()
后者返回一个数组,因此您需要遍历所有返回的元素或通过索引访问您想要的特定元素。
由于您似乎只需要第一个.button
元素,您可以这样做:
var downloadButton = document.getElementsByClassName("button")[0]; // note the [0]
var downloadButton = document.getElementsByClassName("button")[0];
var counter = 10;
var newElement = document.createElement("p");
newElement.innerHTML = "You can download the file in 10 seconds.";
var id;
downloadButton.parentNode.replaceChild(newElement, downloadButton);
id = setInterval(function() {
counter--;
if (counter < 0) {
newElement.parentNode.replaceChild(downloadButton, newElement);
clearInterval(id);
} else {
newElement.innerHTML = "You can download the file in " + counter.toString() + " seconds.";
}
}, 1000);
<a href="downloadFile.zip" class="button">Download the file...</a>
推荐阅读
- capybara - Capybara ingore 在指定断言的“范围内”
- javascript - WDIO - 本地和远程机器中的 isDisplayed() 方法差异
- android - 应用程序未部署在 Google Play 控制台中
- angular - Angular 10 Fullcalendar - 如何编辑事件标题、内容以及如何删除事件?
- python - 使用 Python SDK 创建 Azure 容器时出现“HTTP 标头格式不正确”错误
- google-sheets - 如何通过在谷歌表格/excel中使用每天的开始时间和小时数来找到完成时间?
- javascript - 将导航 html 代码移动到单独的文件,javascript 现在不起作用
- meson-build - Meson:如何运行依赖于外部进程的测试?
- wpf - 拖放:按下 CTRL 时如何显示“移动”光标?
- arrays - 在 Bash 中,如果我只有它的名称,我如何测试数组是否已声明