首页 > 解决方案 > 类不是 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"

请帮我。任何人都可以帮助我吗?拜托我需要你的帮忙。谢谢

标签: javascriptjquerycsshtml

解决方案


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>


推荐阅读