Tengo 2 botones que usan la misma función, necesito poder identificar qué botón presioné.
En el botón 1 pongo onclick="myFunction(1)" y en el botón 2 pongo myFunction(2) y luego en myFunction(a) si uso if condition a=1 no se ejecutará.
<!DOCTYPE html> <html> <body> <!-- CSR --> <label onclick="myFunction(a.value=1)">CSR</label> <input type="text" value="Hello World" id="CSRNm"><br> <!-- Acct# --> <label onclick="myFunction(a.value=2)">Acct#</label> <input type="text" value="Hello Other World" id="AccNo"> <script> function myFunction(a) { if (a.value=1){ navigator.clipboard.writeText(CSRNm.value); /* Alert the copied text */ alert("Copied the text: " + a.value); } else if (a.value=2){ navigator.clipboard.writeText(AccNo.value); /* Alert the copied text */ alert("Copied the text: " + AccNo.value); } } </script> </body> </html>¿Por qué está pasando un valor? Simplemente a.value de la siguiente a :
<button id="btn1" onclick="myFunction(a=1)">one</button> <button id="btn2" onclick="myFunction(a=2)">two</button> const myFunction = (a) => { if (a === 1) { console.log("a"); } if (a === 2) { console.log("b"); } };En vez de:
myFunction(a.value=1)puedes usar esto:
myFunction({value: 1}) La declaración de función para myFunction ya se refiere al parámetro a .
Por lo tanto, cuando pasa el objeto literal {value: 1} como parámetro de función, la función de ejecución devolverá 1 cuando se le a.value .