Мне нужна ваша помощь. У меня есть кнопка загрузки с обратным отсчетом, но есть проблема с кнопкой. Он работает только с первой кнопкой или если сначала нажать на 2-ю кнопку, запускается 1-я кнопка, а не 2-я кнопка. Пожалуйста, помогите мне исправить эту ошибку. Я создал фрагмент с кодировкой. Пожалуйста, просмотрите его и дайте мне знать, что не так! Спасибо.
function generate() {
var e, n = document.getElementById("downloadingx"),
t = document.getElementById("downloadbuttonx"),
a = document.getElementById("downloadingx").href,
l = 10,
d = document.createElement("span");
n.parentNode.replaceChild(d, n), e = setInterval(function() {
--l < 0 ? (d.parentNode.replaceChild(n, d), clearInterval(e), window.open(a), n.style.display = "inline") : (d.innerHTML = "<i class='fa fa-clock-o' aria-hidden='true'/> Redirecting to download page in " + l.toString() + " seconds.", t.style.display = "none")
}, 1e3)
}#downloadbuttonx{
cursor: pointer;
padding: 10px 20px;
border: none;
border-radius: 3px;
background: #fff;
color: #e67e22;
float: none;
text-transform: uppercase;
font-weight: 800;
transition: all 0.5s;
font-size: 16px;
outline: none;
}
#downloadbuttonx:hover,
#downloadingx:hover{
background: #ffffff;
color: #b62727;
outline: none;
}
.batas-downx{
margin: auto;
border-radius: 4px;
display:block;
}
.background-box-st{
background: #b62727;
color: #fff;
padding: 10px 10px 5px 10px;
width: 310px;
text-align: center;
left: 50%;
transform: translate(-50%);
position: relative;
border-top-right-radius:5px;
border-top-left-radius:5px;
border-bottom-right-radius:5px;
border-bottom-left-radius:5px;
line-height: 80px;
margin-bottom: 10px;
}
.background-box-n{
background: #a30085;
color: #fff;
padding: 10px 10px 5px 10px;
width: 310px;
text-align: center;
left: 50%;
transform: translate(-50%);
position: relative;
border-top-right-radius:5px;
border-top-left-radius:5px;
border-bottom-right-radius:5px;
border-bottom-left-radius:5px;
line-height: 80px;
margin-bottom: 10px;
}
.file-name{
font-family: sans-serif;
font-size: 1.3em;
font-weight: 700;
color: #fff;
line-height: 35px;
text-align: center;
display: block;
margin: 5px;
}
.catatan-downx{
padding:20px;
background:#f7f7f7;
color:#555;
font-size:20px;
}
#downloadingx{
display:block;
padding: 10px 20px;
border-radius: 3px;
color: #e67e22;
background: #fff;
text-decoration: none;
text-transform:capitalize;
text-align:center;
float:none;
line-height:80px;
font-size:16px;
font-weight: 600;
}
.bungkus-info span{
display:block;
line-height:80px;
float:none;
}
.file-deskripsi{
display:block;
}
.file-deskripsi span{
margin-right:3px;
}
#downloadbuttonx,
a#downloadingx{
width:160px;
padding:15px;
cursor:pointer;
}
.bungkus-info span{
float:none;
width:100%;
text-align:center;
}
.file-deskripsi{text-align:center}
}<div class = "batas-downx">
<div class = "background-box-n">
<div class = "bungkus-info">
<div class = "file-name">File 1</div>
<button id = "downloadbuttonx" onclick = "generate()"><i aria-hidden = "true" class = "fa fa-cloud-download"></i> Download</button>
<a href = "#" id = "downloadingx" style = "display: none;"><i aria-hidden = "true" class = "fa fa-cloud-download"></i> Redirecting...</a>
</div>
</div>
</div>
<br>
<div class = "batas-downx">
<div class = "background-box-st">
<div class = "bungkus-info">
<div class = "file-name">File 1</div>
<button id = "downloadbuttonx" onclick = "generate()"><i aria-hidden = "true" class = "fa fa-cloud-download"></i> Download</button>
<a href = "#" id = "downloadingx" style = "display: none;"><i aria-hidden = "true" class = "fa fa-cloud-download"></i> Redirecting...</a>
</div>
</div>
</div>Привет @NotABot! Тогда что мне использовать? Какой будет код?
@НеБот! Не могли бы вы создать фрагмент с решением. Пожалуйста!



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Один из способов — передать идентификатор кнопки с помощью this.id, а затем использовать этот идентификатор, чтобы узнать, какая кнопка нажата.
См. приведенный ниже пример.
function generate(idOfButtonClicked){
console.info("ID is: ", idOfButtonClicked)
}<button id = "btn-1" onclick = "generate(this.id)"> Click Me</button>
<br />
<button id = "btn-2" onclick = "generate(this.id)"> Click Me</button>Теперь, перейдя к вашему коду, вы можете передать идентификатор в качестве параметров функции generate().
Кроме того, необходимо иметь некоторый идентификатор downloadingx для каждого тега <a>, вы можете иметь что-то подобное в качестве идентификатора для каждого downloadingx-btn-download-1 и downloadingx-btn-download-2 соответственно.
Дело в том, что нельзя иметь одинаковый ID для разных элементов на странице.
function generate(btnId) {
var e, n = document.getElementById(btnId),
t = document.getElementById(btnId),
a = document.getElementById("downloadingx-"+btnId).href,
l = 10,
d = document.createElement("span");
n.parentNode.replaceChild(d, n), e = setInterval(function() {
--l < 0 ? (d.parentNode.replaceChild(n, d), clearInterval(e), window.open(a), n.style.display = "inline") : (d.innerHTML = "<i class='fa fa-clock-o' aria-hidden='true'/> Redirecting to download page in " + l.toString() + " seconds.", t.style.display = "none")
}, 1e3)
}#downloadbuttonx{
cursor: pointer;
padding: 10px 20px;
border: none;
border-radius: 3px;
background: #fff;
color: #e67e22;
float: none;
text-transform: uppercase;
font-weight: 800;
transition: all 0.5s;
font-size: 16px;
outline: none;
}
#downloadbuttonx:hover,
#downloadingx:hover{
background: #ffffff;
color: #b62727;
outline: none;
}
.batas-downx{
margin: auto;
border-radius: 4px;
display:block;
}
.background-box-st{
background: #b62727;
color: #fff;
padding: 10px 10px 5px 10px;
width: 310px;
text-align: center;
left: 50%;
transform: translate(-50%);
position: relative;
border-top-right-radius:5px;
border-top-left-radius:5px;
border-bottom-right-radius:5px;
border-bottom-left-radius:5px;
line-height: 80px;
margin-bottom: 10px;
}
.background-box-n{
background: #a30085;
color: #fff;
padding: 10px 10px 5px 10px;
width: 310px;
text-align: center;
left: 50%;
transform: translate(-50%);
position: relative;
border-top-right-radius:5px;
border-top-left-radius:5px;
border-bottom-right-radius:5px;
border-bottom-left-radius:5px;
line-height: 80px;
margin-bottom: 10px;
}
.file-name{
font-family: sans-serif;
font-size: 1.3em;
font-weight: 700;
color: #fff;
line-height: 35px;
text-align: center;
display: block;
margin: 5px;
}
.catatan-downx{
padding:20px;
background:#f7f7f7;
color:#555;
font-size:20px;
}
#downloadingx{
display:block;
padding: 10px 20px;
border-radius: 3px;
color: #e67e22;
background: #fff;
text-decoration: none;
text-transform:capitalize;
text-align:center;
float:none;
line-height:80px;
font-size:16px;
font-weight: 600;
}
.bungkus-info span{
display:block;
line-height:80px;
float:none;
}
.file-deskripsi{
display:block;
}
.file-deskripsi span{
margin-right:3px;
}
#downloadbuttonx,
a#downloadingx{
width:160px;
padding:15px;
cursor:pointer;
}
.bungkus-info span{
float:none;
width:100%;
text-align:center;
}
.file-deskripsi{text-align:center}
}<div class = "batas-downx">
<div class = "background-box-n">
<div class = "bungkus-info">
<div class = "file-name">File 1</div>
<button id = "btn-download-1" onclick = "generate(this.id)"><i aria-hidden = "true" class = "fa fa-cloud-download"></i> Download</button>
<a href = "#" id = "downloadingx-btn-download-1" style = "display: none;"><i aria-hidden = "true" class = "fa fa-cloud-download"></i> Redirecting...</a>
</div>
</div>
</div>
<br>
<div class = "batas-downx">
<div class = "background-box-st">
<div class = "bungkus-info">
<div class = "file-name">File 2</div>
<button id = "btn-download-2" onclick = "generate(this.id)"><i aria-hidden = "true" class = "fa fa-cloud-download"></i> Download</button>
<a href = "#" id = "downloadingx-btn-download-2" style = "display: none;"><i aria-hidden = "true" class = "fa fa-cloud-download"></i> Redirecting...</a>
</div>
</div>
</div>Я думаю, вы можете добавить класс CSS, например .download_btn, чтобы уменьшить код CSS. Прошу прощения за мой плохой английский.
Привет, @Not A Bot, у меня твое решение работает нормально, но есть две небольшие проблемы. 1: Когда я нажимаю «Загрузить», размер кнопки уменьшается до заголовка файла, а затем возвращается к исходному размеру, когда начинается таймер. При этом размер должен оставаться прежним. 2: При замедленной съемке должно появиться «Перенаправление...», тогда как снова появится кнопка «Загрузить». Есть ли способы исправить эти проблемы?
Попробуй это
function generate(buttonId,hrefId) {
var e, n = document.getElementById(hrefId),
t = document.getElementById(buttonId),
a = document.getElementById(hrefId).href,
l = 10,
d = document.createElement("span");
n.parentNode.replaceChild(d, n), e = setInterval(function() {
--l < 0 ? (d.parentNode.replaceChild(n, d), clearInterval(e), window.open(a), n.style.display = "inline") : (d.innerHTML = "<i class='fa fa-clock-o' aria-hidden='true'/> Redirecting to download page in " + l.toString() + " seconds.", t.style.display = "none")
}, 1e3)
}
<div class = "batas-downx">
<div class = "background-box-n">
<div class = "bungkus-info">
<div class = "file-name">File 1</div>
<button id = "downloadbuttonx0" onclick = "generate('downloadbuttonx0','downloadingx0')"><i aria-hidden = "true" class = "fa fa-cloud-download"></i> Download</button>
<a href = "#" id = "downloadingx0" style = "display: none;"><i aria-hidden = "true" class = "fa fa-cloud-download"></i> Redirecting...</a>
</div>
</div>
</div>
<br>
<div class = "batas-downx">
<div class = "background-box-st">
<div class = "bungkus-info">
<div class = "file-name">File 1</div>
<button id = "downloadbuttonx1" onclick = "generate('downloadbuttonx1','downloadingx1')"><i aria-hidden = "true" class = "fa fa-cloud-download"></i> Download</button>
<a href = "#" id = "downloadingx1" style = "display: none;"><i aria-hidden = "true" class = "fa fa-cloud-download"></i> Redirecting...</a>
</div>
</div>
</div>
Идеальный 👍 Еще раз большое спасибо.
Я нашел твою ошибку. Дело в том, что первая кнопка «Скачать» и вторая имели одинаковый идентификатор. Я решаю, изменив идентификатор второго.
function generatex() {
var e, n = document.getElementById("downloadingx"),
t = document.getElementById("downloadbuttonx"),
a = document.getElementById("downloadingx").href,
l = 10,
d = document.createElement("span");
n.parentNode.replaceChild(d, n), e = setInterval(function() {
--l < 0 ? (d.parentNode.replaceChild(n, d), clearInterval(e), window.open(a), n.style.display = "inline") : (d.innerHTML = "<i class='fa fa-clock-o' aria-hidden='true'/> Redirecting to download page in " + l.toString() + " seconds.", t.style.display = "none")
}, 1e3)
}
function generatey() {
var e, n = document.getElementById("downloadingy"),
t = document.getElementById("downloadbuttony"),
a = document.getElementById("downloadingy").href,
l = 10,
d = document.createElement("span");
n.parentNode.replaceChild(d, n), e = setInterval(function() {
--l < 0 ? (d.parentNode.replaceChild(n, d), clearInterval(e), window.open(a), n.style.display = "inline") : (d.innerHTML = "<i class='fa fa-clock-o' aria-hidden='true'/> Redirecting to download page in " + l.toString() + " seconds.", t.style.display = "none")
}, 1e3)
}
css
#downloadbuttonx{
cursor: pointer;
padding: 10px 20px;
border: none;
border-radius: 3px;
background: #fff;
color: #e67e22;
float: none;
text-transform: uppercase;
font-weight: 800;
transition: all 0.5s;
font-size: 16px;
outline: none;
}
#downloadbuttony{
cursor: pointer;
padding: 10px 20px;
border: none;
border-radius: 3px;
background: #fff;
color: #e67e22;
float: none;
text-transform: uppercase;
font-weight: 800;
transition: all 0.5s;
font-size: 16px;
outline: none;
}
#downloadbuttonx:hover,
#downloadingx:hover{
background: #ffffff;
color: #b62727;
outline: none;
}
#downloadbuttony:hover,
#downloadingy:hover{
background: #ffffff;
color: #b62727;
outline: none;
}
.batas-downx{
margin: auto;
border-radius: 4px;
display:block;
}
.batas-downy{
margin: auto;
border-radius: 4px;
display:block;
}
.background-box-st{
background: #b62727;
color: #fff;
padding: 10px 10px 5px 10px;
width: 310px;
text-align: center;
left: 50%;
transform: translate(-50%);
position: relative;
border-top-right-radius:5px;
border-top-left-radius:5px;
border-bottom-right-radius:5px;
border-bottom-left-radius:5px;
line-height: 80px;
margin-bottom: 10px;
}
.background-box-n{
background: #a30085;
color: #fff;
padding: 10px 10px 5px 10px;
width: 310px;
text-align: center;
left: 50%;
transform: translate(-50%);
position: relative;
border-top-right-radius:5px;
border-top-left-radius:5px;
border-bottom-right-radius:5px;
border-bottom-left-radius:5px;
line-height: 80px;
margin-bottom: 10px;
}
.file-name{
font-family: sans-serif;
font-size: 1.3em;
font-weight: 700;
color: #fff;
line-height: 35px;
text-align: center;
display: block;
margin: 5px;
}
.catatan-downx{
padding:20px;
background:#f7f7f7;
color:#555;
font-size:20px;
}
.catatan-downy{
padding:20px;
background:#f7f7f7;
color:#555;
font-size:20px;
}
#downloadingx{
display:block;
padding: 10px 20px;
border-radius: 3px;
color: #e67e22;
background: #fff;
text-decoration: none;
text-transform:capitalize;
text-align:center;
float:none;
line-height:80px;
font-size:16px;
font-weight: 600;
}
#downloadingy{
display:block;
padding: 10px 20px;
border-radius: 3px;
color: #e67e22;
background: #fff;
text-decoration: none;
text-transform:capitalize;
text-align:center;
float:none;
line-height:80px;
font-size:16px;
font-weight: 600;
}
.bungkus-info span{
display:block;
line-height:80px;
float:none;
}
.file-deskripsi{
display:block;
}
.file-deskripsi span{
margin-right:3px;
}
#downloadbuttonx,
#downloadbuttony,
a#downloadingx,
a#downloadingy{
width:160px;
padding:15px;
cursor:pointer;
}
.bungkus-info span{
float:none;
width:100%;
text-align:center;
}
.file-deskripsi{text-align:center}
}
HTML
<div class = "batas-downx">
<div class = "background-box-n">
<div class = "bungkus-info">
<div class = "file-name">File 1</div>
<button id = "downloadbuttonx" onclick = "generatex()"><i aria-hidden = "true" class = "fa fa-cloud-download"></i> Download</button>
<a href = "#" id = "downloadingx" style = "display: none;"><i aria-hidden = "true" class = "fa fa-cloud-download"></i> Redirecting...</a>
</div>
</div>
</div>
<br>
<div class = "batas-downx">
<div class = "background-box-st">
<div class = "bungkus-info">
<div class = "file-name">File 1</div>
<button id = "downloadbuttony" onclick = "generatey()"><i aria-hidden = "true" class = "fa fa-cloud-download"></i> Download</button>
<a href = "#" id = "downloadingy" style = "display: none;"><i aria-hidden = "true" class = "fa fa-cloud-download"></i> Redirecting...</a>
</div>
</div>
</div>
Вы можете добавить класс, например, downloadBtn, чтобы уменьшить код CSS. Прошу прощения за мой плохой английский.
Пожалуйста. В stackoverflow все помогают другим. Я мало что знаю, но своим знанием помогу другим.
Есть гораздо лучшие способы, чем дублировать такой код.
Конечно вы можете. Я думаю, что коды css и js можно сократить, как определение классов.
Привет, @George, твое решение было простым, но ты дублируешь javascript, что увеличивает размер javascript. Есть ли лучший способ? Потому что, если мне нужно добавить третью кнопку, я должен добавить Javascript этой кнопки вместе с HTML.
Вы действительно должны зарегистрировать свои прослушиватели событий в JavaScript. Это позволит вам использовать this внутри generate для ссылки на элемент, к которому был привязан прослушиватель событий.
Оттуда легко найти соответствующий якорь (<a>) с помощью nextElementSibling.
Дополнительным преимуществом является то, что вам не нужно придумывать разные идентификаторы для кнопок и элементов привязки, если у вас большой список (я избавился от них).
(function() {
function generate() {
var e, n = this.nextElementSibling,
t = this,
a = this.nextElementSibling.href,
l = 10,
d = document.createElement("span");
n.parentNode.replaceChild(d, n), e = setInterval(function() {
--l < 0 ? (d.parentNode.replaceChild(n, d), clearInterval(e), window.open(a), n.style.display = "inline") : (d.innerHTML = "<i class='fa fa-clock-o' aria-hidden='true'/> Redirecting to download page in " + l.toString() + " seconds.", t.style.display = "none")
}, 1e3)
}
const buttons = document.getElementsByTagName('button');
for (let i = 0; i < buttons.length; i++) {
const button = buttons[i];
button.addEventListener('click', generate);
}
})();.downloadbuttonx {
cursor: pointer;
padding: 10px 20px;
border: none;
border-radius: 3px;
background: #fff;
color: #e67e22;
float: none;
text-transform: uppercase;
font-weight: 800;
transition: all 0.5s;
font-size: 16px;
outline: none;
}
.downloadbuttonx:hover,
.downloadingx:hover {
background: #ffffff;
color: #b62727;
outline: none;
}
.batas-downx {
margin: auto;
border-radius: 4px;
display: block;
}
.background-box-st {
background: #b62727;
color: #fff;
padding: 10px 10px 5px 10px;
width: 310px;
text-align: center;
left: 50%;
transform: translate(-50%);
position: relative;
border-top-right-radius: 5px;
border-top-left-radius: 5px;
border-bottom-right-radius: 5px;
border-bottom-left-radius: 5px;
line-height: 80px;
margin-bottom: 10px;
}
.background-box-n {
background: #a30085;
color: #fff;
padding: 10px 10px 5px 10px;
width: 310px;
text-align: center;
left: 50%;
transform: translate(-50%);
position: relative;
border-top-right-radius: 5px;
border-top-left-radius: 5px;
border-bottom-right-radius: 5px;
border-bottom-left-radius: 5px;
line-height: 80px;
margin-bottom: 10px;
}
.file-name {
font-family: sans-serif;
font-size: 1.3em;
font-weight: 700;
color: #fff;
line-height: 35px;
text-align: center;
display: block;
margin: 5px;
}
.catatan-downx {
padding: 20px;
background: #f7f7f7;
color: #555;
font-size: 20px;
}
.downloadingx {
display: block;
padding: 10px 20px;
border-radius: 3px;
color: #e67e22;
background: #fff;
text-decoration: none;
text-transform: capitalize;
text-align: center;
float: none;
line-height: 80px;
font-size: 16px;
font-weight: 600;
}
.bungkus-info span {
display: block;
line-height: 80px;
float: none;
}
.file-deskripsi {
display: block;
}
.file-deskripsi span {
margin-right: 3px;
}
.downloadbuttonx,
a.downloadingx {
width: 160px;
padding: 15px;
cursor: pointer;
}
.bungkus-info span {
float: none;
width: 100%;
text-align: center;
}
.file-deskripsi {
text-align: center
}<div class = "batas-downx">
<div class = "background-box-n">
<div class = "bungkus-info">
<div class = "file-name">File 1</div>
<button class = "downloadbuttonx"><i aria-hidden = "true" class = "fa fa-cloud-download"></i> Download</button>
<a href = "#" class = "downloadingx" style = "display: none;"><i aria-hidden = "true" class = "fa fa-cloud-download"></i> Redirecting...</a>
</div>
</div>
</div>
<br>
<div class = "batas-downx">
<div class = "background-box-st">
<div class = "bungkus-info">
<div class = "file-name">File 2</div>
<button class = "downloadbuttonx"><i aria-hidden = "true" class = "fa fa-cloud-download"></i> Download</button>
<a href = "#" class = "downloadingx" style = "display: none;"><i aria-hidden = "true" class = "fa fa-cloud-download"></i> Redirecting...</a>
</div>
</div>
</div>ОБНОВЛЕНИЕ Повторно включена стилизация без использования повторяющихся идентификаторов с использованием вместо этого классов CSS.
Привет, @phuzi, твое решение отлично работает для меня, но ты удалил мой стиль, который был необходим.
не могли бы вы отредактировать javascript и добавить стили (downloadbuttonx и downloadingx)?
Я могу, но они не нужны для вопроса или ответа.
Потому что у вас не может быть одного и того же идентификатора, то есть
downloadingxдля двух разных элементов. Обе ваши кнопки имеют одинаковый идентификатор, поэтому javascript нацеливается на первый идентификатор каждый раз, когда вы нажимаете вторую кнопку.