Anonymous
Способ получить идентификатор элемента при нажатии, используя его в качестве обработчика событий
Сообщение
Anonymous » 29 ноя 2024, 01:07
Я запрограммировал индикатор выполнения загрузки. При нажатии на элемент начинается загрузка и отображается ход загрузки. К сожалению, я не могу заставить его работать с несколькими кнопками, и я не знаю вариантов.
Подробнее, что я ищу: при нажатии он получает идентификатор вызывающего элемента и предполагаемый файл. для загрузки при нажатии кнопки {num}. Затем используйте идентификатор обработчика событий и загрузите файл.
Первое сообщение здесь, так что скажите мне, что мне следует сделать по-другому.
Заранее спасибо .
Код: Выделить всё
const fileToDownload = 'img/jdk-22_windows-x64_bin.exe';
const startDownloadElem = document.getElementById('startDownload');
const downloadProgressElem = document.querySelector(
'.download-progress-bar__progress'
);
console.log('Initially ' + (window.navigator.onLine ? 'on' : 'off') + 'line');
window.addEventListener('online', () => console.log('Became online'));
window.addEventListener('offline', () => console.log('Became offline'));
//document.getElementById('statusCheck').addEventListener('click', () => console.log('window.navigator.onLine is ' + window.navigator.onLine));
startDownloadElem.addEventListener('click', () => {
// downloadProgressElem.style.background = 'linear-gradient(to right, rgba(255, 0, 0, 0), rgb(255, 0, 0))';
console.log('Download Started');
startDownloadElem.setAttribute('disabled', 'true');
const dataChunks = [];
fetch(`/${fileToDownload}`)
.then(response => {
const reader = response.body.getReader();
const totalSize = Number(
response.headers.get('content-length')
);
let totalSizeDownloaded = 0;
downloadProgressElem.classList.remove('error');
function readData() {
return reader.read().then(result => {
if (result.value) {
dataChunks.push(result.value);
totalSizeDownloaded += result.value.length;
const percentage = Math.floor(
(totalSizeDownloaded / totalSize) * 100
);
console.log(
`${totalSizeDownloaded}/${totalSize} (${percentage}%)`
);
downloadProgressElem.textContent = `${percentage}%`;
downloadProgressElem.style.width = `${percentage}%`;
}
if (!result.done) {
return readData();
}
});
}
return readData();
})
.then(() => {
console.log('Download finished');
const downloadAnchor = document.createElement('a');
const blob = new Blob(dataChunks);
downloadAnchor.href = URL.createObjectURL(blob);
downloadAnchor.download = fileToDownload;
document.body.appendChild(downloadAnchor);
downloadAnchor.click();
document.body.removeChild(downloadAnchor);
})
.catch( () => {
downloadProgressElem.textContent = 'Download error';
downloadProgressElem.classList.add('error');
})
.finally(() => {
startDownloadElem.removeAttribute('disabled');
})
})
Код: Выделить всё
html {
height: 100%;
}
body {
height: 100%;
}
#startDownload {
background: #c50408;
color: honeydew;
padding: 10px;
}
#startDownload:disabled {
background-color: rgb(39, 92, 74);
}
.button-and-progress-div {
display: flex;
flex-flow: nowrap column;
align-items: center;
justify-content: center;
height: 100%;
}
.download-progress-bar__container {
margin: 20px 0;
width: 400px;
height: 40px;
border-radius: 10px;
}
.download-progress-bar__progress {
background: linear-gradient(to right, rgba(255, 0, 0, 0), rgb(255, 0, 0));
border-radius: 10px;
color: honeydew;
display: flex;
align-items: center;
justify-content: center;
width: 0;
height: 100%;
}
.download-progress-bar__progress.error {
background: linear-gradient(to right, rgba(138, 0, 226, 0), rgb(138, 0, 226, 1));
}
Подробнее здесь:
https://stackoverflow.com/questions/792 ... enthandler
1732831652
Anonymous
Я запрограммировал индикатор выполнения загрузки. При нажатии на элемент начинается загрузка и отображается ход загрузки. К сожалению, я не могу заставить его работать с несколькими кнопками, и я не знаю вариантов. Подробнее, что я ищу: при нажатии он получает идентификатор вызывающего элемента и предполагаемый файл. для загрузки при нажатии кнопки {num}. Затем используйте идентификатор обработчика событий и загрузите файл. Первое сообщение здесь, так что скажите мне, что мне следует сделать по-другому. Заранее спасибо . [code]const fileToDownload = 'img/jdk-22_windows-x64_bin.exe'; const startDownloadElem = document.getElementById('startDownload'); const downloadProgressElem = document.querySelector( '.download-progress-bar__progress' ); console.log('Initially ' + (window.navigator.onLine ? 'on' : 'off') + 'line'); window.addEventListener('online', () => console.log('Became online')); window.addEventListener('offline', () => console.log('Became offline')); //document.getElementById('statusCheck').addEventListener('click', () => console.log('window.navigator.onLine is ' + window.navigator.onLine)); startDownloadElem.addEventListener('click', () => { // downloadProgressElem.style.background = 'linear-gradient(to right, rgba(255, 0, 0, 0), rgb(255, 0, 0))'; console.log('Download Started'); startDownloadElem.setAttribute('disabled', 'true'); const dataChunks = []; fetch(`/${fileToDownload}`) .then(response => { const reader = response.body.getReader(); const totalSize = Number( response.headers.get('content-length') ); let totalSizeDownloaded = 0; downloadProgressElem.classList.remove('error'); function readData() { return reader.read().then(result => { if (result.value) { dataChunks.push(result.value); totalSizeDownloaded += result.value.length; const percentage = Math.floor( (totalSizeDownloaded / totalSize) * 100 ); console.log( `${totalSizeDownloaded}/${totalSize} (${percentage}%)` ); downloadProgressElem.textContent = `${percentage}%`; downloadProgressElem.style.width = `${percentage}%`; } if (!result.done) { return readData(); } }); } return readData(); }) .then(() => { console.log('Download finished'); const downloadAnchor = document.createElement('a'); const blob = new Blob(dataChunks); downloadAnchor.href = URL.createObjectURL(blob); downloadAnchor.download = fileToDownload; document.body.appendChild(downloadAnchor); downloadAnchor.click(); document.body.removeChild(downloadAnchor); }) .catch( () => { downloadProgressElem.textContent = 'Download error'; downloadProgressElem.classList.add('error'); }) .finally(() => { startDownloadElem.removeAttribute('disabled'); }) })[/code] [code]html { height: 100%; } body { height: 100%; } #startDownload { background: #c50408; color: honeydew; padding: 10px; } #startDownload:disabled { background-color: rgb(39, 92, 74); } .button-and-progress-div { display: flex; flex-flow: nowrap column; align-items: center; justify-content: center; height: 100%; } .download-progress-bar__container { margin: 20px 0; width: 400px; height: 40px; border-radius: 10px; } .download-progress-bar__progress { background: linear-gradient(to right, rgba(255, 0, 0, 0), rgb(255, 0, 0)); border-radius: 10px; color: honeydew; display: flex; align-items: center; justify-content: center; width: 0; height: 100%; } .download-progress-bar__progress.error { background: linear-gradient(to right, rgba(138, 0, 226, 0), rgb(138, 0, 226, 1)); }[/code] [code] Download [/code] Подробнее здесь: [url]https://stackoverflow.com/questions/79235285/a-way-to-get-element-id-on-click-while-using-it-as-eventhandler[/url]