我如何使这段代码有效
<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"
请帮帮我。有人可以帮帮我吗?拜托我需要你的帮忙。感谢
答案 0 :(得分:2)
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);
&#13;
<a href="downloadFile.zip" class="button">Download the file...</a>
&#13;