Как я могу заставить этот код работать
<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>
Нет проблем, рад помочь
var downloadButton = document.getElementsByClassName("button")[0];
, потому чтоdocument.getElementsByClassName()
возвращает массив