简体   繁体   中英

Why this simple call in JavaScript doesn't work?

I'm just starting with JavaScript and I got in some troubles trying to understand why somethings doesn't work as they should. In this particular case I don't understand why if I call a function that calls another function, as parameter, the second one works and the first doesn't. If I call directly the second function then it doesn't work either. So the only way I found to make it work is by calling the second function through the first one and making the second function do also the job of the first one.

Can anyone tell me where is the problem and why?

 function resultado(texto) { document.getElementById("mayor").innerHTML = texto; } function comparar() { var n1, n2, n3, texto; n1 = document.getElementById("n1").value; n2 = document.getElementById("n2").value; n3 = document.getElementById("n3").value; if (isNaN(n1) || isNaN(n2) || isNaN(n3)) { document.getElementById("mayor").innerHTML = "Deben ser números"; } n1 = parseInt(n1); n2 = parseInt(n2); n3 = parseInt(n3); texto = "El mayor es: "; if (n1 < n2) { if (n2 < n3) texto += n3 + " "; else texto += n2 + " "; } else { if (n1 < n3) texto += n3 + " "; else texto += n1 + " "; } document.getElementById("mayor").innerHTML = texto; return texto; }
 <div id="fondo"> <div id="contenido"> <h1 id="titulo">El mayor de 3</h1> <p>Introduce 3 números enteros:</p> <label for="n1">Número 1: </label> <input value="0" name="n1" id="n1" size="4"><br> <label for="n2">Número 2: </label> <input value="0" name="n2" id="n2" size="4"><br> <label for="n3">Número 3: </label> <input value="0" name="n3" id="n3" size="4"> <button type="button" onclick="document.resultado(comparar());">¿mayor?</button> <br> <p id="mayor"></p> </div> </div>

Remove documento from onclick, It will be like this onclick="resultado(comparar());"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM