我有一个音乐播放器,我可以通过链接直接链接到点击功能下载音频文件。每个音频文件都在li元素中,只要我保持它的硬编码,一切都可以正常工作。但是当我将li元素和下载链接转换为dynamic时,我就不能再连接点击功能了。有人能帮忙吗?下面是代码:
//Html硬编码
<ul id="playlist1" class="hidden m-1 p-0">
<li id="li-items" data-song="the-deal.wav">The Deal<span class="dwn fa fa-download" onclick="downloadFile('/audio/the-deal.wav', 'The Deal')"></span></li>
<li id="li-items" data-song="rise-of-don.mp3">Rise of The Don<span class="dwn fa fa-download" onclick="downloadFile('/media/rise-of-don.mp3', 'Rise of The Don')"></span></li>
</ul>
//Audio Library js
var data1 = [{
href: "/media/the-deal.wav",
name: "The Deal",
song: "the-deal.wav"
}, {
href: "/media/rise-of-don.mp3",
name: "Rise of the Don",
song: "rise-of-don.mp3"
}]
// Create li elements
for (var i = 0; i < data1.length; i++) {
var t = document.createElement('li');
t.setAttribute("id","li-items");
var ta = document.createElement('span');
ta.classList.add("dwn","fa","fa-download");
ta.setAttribute("onclick","downloadFile('url','filename')"); // << This is the line that I'm having trouble with. 'Url' and 'filename' should be added dynamically for each li element.
t.dataset.song = s.song;
t.textContent = s.name;
t.appendChild(ta);
document.getElementById('playlist1').appendChild(t);
}
//音频播放器js -(下载功能):
function downloadFile(url, filename) {
//Filename download the user-defined name. The URL is the download address
var link = document.createElement('a');
link.href = url;
link.download = filename;
link.target = '_blank';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
link = null;
}
如果有人能帮忙,我将非常感激。
我想在这一行
ta.setAttribute("onclick","downloadFile('url','filename')");
使用string作为属性。也许你可以
// ta.setAttribute("data-href", data[i].href)
// ta.setAttribute("value", data[i].name)
// You can also
ta.dataset.href = data[i].href
ta.dataset.name = data[i].name
ta.addEventListener("click", downloadFile)
然后在downloadFile
function downloadFile(e) {
fileUrl = e.dataset.href
fileName = e.dataset.name
console.log(fileUrl, fileName)
// continue with your actions
}
更多关于数据集的信息——https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset
var data1 = [
// ...
]
创建列表项:
const playList = document.querySelector('#playlist1')
data1.forEach((data, i) => {
const list = document.createElement('li');
list.setAttribute('class', 'song-items');
list.dataset.index = i;
list.textContent = data.name;
const listInner = document.createElement('span');
listInner.classList.add('dwn', 'fa', 'fa-download');
list.appendChild(listInner);
playList.appendChild(list);
})
检查点击事件:
document.querySelectorAll('.song-items').forEach(item => {
item.addEventListener('click', () => {
const index = item.getAttribute('data-index');
const { href, name } = data1[index];
downloadFile(href, name);
})
})
下载功能:
function downloadFile(url, filename) {
console.log(filename, url)
// ...
}