Tengo una página HTML que tiene javascript, me gustaría que javascript genere botones HTML como este:
<button class="btnFormat" onclick="var link = document.createElement('a'); link.href = '#xxxxx'; link.click(); window.location.reload() "> AYOU1 </button> <button class="btnFormat" onclick="var link = document.createElement('a'); link.href = '#xxxxx'; link.click(); window.location.reload() "> AYOU1 </button> <button class="btnFormat" onclick="var link = document.createElement('a'); link.href = '#xxxxx'; link.click(); window.location.reload() "> AYOU1 </button>Parece que no puedo entender cómo obtener el javascript para agregar la clase o hacer clic en 'cadenas'. Mi código se ejecuta sin errores, pero mirando el resultado es solo:
<button>AYOU1</button> <button>AYOU2</button> <button>AYOU3</button>Este es el código en el que he estado trabajando (no tiene class=, ya que no puedo descifrar la parte onClick=...):
<html> <body> <script> var items = [ {hex: "OBFPUOX6T", alpha: "AYOU1" }, {hex: "LC7THLODH", alpha: "AYOU2" }, {hex: "RNPODALAJ", alpha: "AYOU3" }, {hex: "2FSCQ4LGK", alpha: "AYOU4" }, ] var i = 0; const parentElement = document.querySelector('body'); // DOM location when buttons will be added items.forEach(function(item) { const pButton = document.createElement("button"); pButton.innerText = item.alpha; pButton.onClick = function() { var link = document.createElement('a'); link.href = '#' + item.hex; window.location.reload(); }; i++; console.log(pButton, i) parentElement.appendChild(pButton); // to add new element to DOM }) </script> </body> </html>¡Apreciaría cualquier ayuda! ¡Gracias de antemano!
Agregué el código fuente completo aquí: https://jsfiddle.net/kilimar/7eL15azm/
Si su salida no muestra ninguna clase, es porque todos los eventos se manejan en segundo plano, probablemente también sea una buena práctica hacerlo de esa manera.
Sin embargo, su secuencia de comandos tiene algunos errores y se puede simplificar:
pButton.onclick está en minúsculas (no pButton.onClick )
pButton.onclick = function() { // [...] Luego hay una propiedad muy útil: location.hash (también window no es necesaria)
location.hash = '#' + item.hex; location.reload(); (¡Bonificación!) hay un atajo para document.querySelector('body')
const parentElement = document.bodyDe todos modos, aquí está el código completo:
<!DOCTYPE html> <html> <head> </head> <body> <script> var items = [ {hex: "OBFPUOX6T", alpha: "AYOU1"}, {hex: "LC7THLODH", alpha: "AYOU2"}, {hex: "RNPODALAJ", alpha: "AYOU3"}, {hex: "2FSCQ4LGK", alpha: "AYOU4"}, ] var i = 0; const parentElement = document.body; // DOM location when buttons will be added items.forEach(function(item) { const pButton = document.createElement("button"); pButton.innerText = item.alpha; pButton.onclick = function() { location.hash = '#' + item.hex; location.reload(); }; i++; console.log(pButton, i) parentElement.appendChild(pButton); // to add new element to DOM }) </script> </body> </html>¡Espero que esto haya ayudado!