Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

357
Views
¿Hay alguna forma de agregar valores dinámicamente a una función onclick?

Tengo un reproductor de música en el que puedo descargar archivos de audio vinculando el href directamente a una función de clic. Cada archivo de audio está en un elemento li y todo funciona bien siempre que lo mantenga codificado. Pero en el momento en que convierto los elementos li y el enlace de descarga en dinámico, ya no puedo conectar la función de clic. ¿Alguien puede ayudar? Aquí está el código:

// HTML codificado

 <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>

// Biblioteca de audio 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); }

// Reproductor de audio js - (función de descarga):

 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; }

Si alguien pudiera ayudar, realmente lo agradecería.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Supuse que en esta línea

 ta.setAttribute("onclick","downloadFile('url','filename')");

Está utilizando una cadena como atributo. tal vez podrías

 // 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)

Y luego en el archivo de downloadFile

 function downloadFile(e) { fileUrl = e.dataset.href fileName = e.dataset.name console.log(fileUrl, fileName) // continue with your actions }

Más sobre conjuntos de datos -- https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset

about 4 years ago · Juan Pablo Isaza Report

0

var data1 = [ // ... ]

Crear elementos de lista:

 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); })

Compruebe el evento de clic:

 document.querySelectorAll('.song-items').forEach(item => { item.addEventListener('click', () => { const index = item.getAttribute('data-index'); const { href, name } = data1[index]; downloadFile(href, name); }) })

Función de descarga:

 function downloadFile(url, filename) { console.log(filename, url) // ... }
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!