tengo página HTML muy simple con código JS:Javascript - asignar dinámicamente evento onclick en el bucle
<html>
<head>
<title></title>
</head>
<body>
<div id="divButtons">
</div>
<script type="text/javascript">
var arrOptions = new Array();
for (var i = 0; i < 10; i++) {
arrOptions[i] = "option" + i;
}
for (var i = 0; i < arrOptions.length; i++) {
var btnShow = document.createElement("input");
btnShow.setAttribute("type", "button");
btnShow.value = "Show Me Option";
var optionPar = arrOptions[i];
btnShow.onclick = function() {
showParam(optionPar);
}
document.getElementById('divButtons').appendChild(btnShow);
}
function showParam(value) {
alert(value);
}
</script>
</body>
</html>
Esa página se une 10 botones, pero al hacer clic en cualquier botón que muestra siempre alerta "option9". ¿Cómo es posible asignar el evento onclick para mostrar la opción correspondiente?
Gracias!
¿Qué está pasando realmente aquí? Esto funcionó para mí aswell, pero quiero entender aswell :-) – MartinElvar
@MartinElvar creó una función que los argumentos son opt, a continuación, cuando aplicamos el (...) (arrOptions [i]) y luego se pasó a optar y luego cuando hacemos clic en btnShow, esta función se llama con los parámetros que se han establecido. – Yehonatan
Una mejor manera, que no es tan confusa es usar el atributo "data" del nodo, y luego usar this.data como el parámetro de la función. Aquí hay un ejemplo: 'btnShow.data = arrOptions [i]; btnShow.onclick = function() { showParam (this.data); } ' –