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

124
Views
Para event.target en onclick - "TypeError TypeError no detectado: no se pueden establecer propiedades de indefinido (estableciendo 'valor')"

Estoy tratando de hacer que mi html llame a una función javascript al hacer clic en la que la función misma hace referencia al evento que la llamó, pero sigo recibiendo este error:

 Uncaught TypeError TypeError: Cannot set properties of undefined (setting 'value') at play (c:\Users\C2Ran\Desktop\Practice\app.js:5:16) at onclick (c:\Users\C2Ran\Desktop\Practice\index.html:24:68)

Aquí está mi html:

 <!DOCTYPE html> <head> <link rel="stylesheet" href="style.css"> <script type="text/javascript" src="app.js" defer></script> </head> <body> <input type="button" value="X" id="turn" onclick="play(this);"> </body> </html>

Aquí está mi javascript:

 var turn = "X" function play(event) { var cell = event.target; cell.value = turn; console.log(turn); if(turn == "X") { turn = "O" } else { turn = "X" } }

¿Se me escapa algo? ¿Por qué dice que el value no está definido? ¿No está obteniendo el evento correctamente? ¿O onclick no cuenta como un evento? También probé event.currentTarget en su lugar

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

0

Evite usar llamadas a funciones en atributos HTML, en su lugar use addEventListener ,

Su problema es que está usando this cuando debería estar usando event.currentTarget

Nota: He mejorado un poco tu código en la función play()

 function play(cell) { cell.value = cell.value === "X" ? "O" : "X" console.log(cell.value); } document.getElementById('turn').addEventListener('click', e => play(e.currentTarget))
 <input type="button" value="X" id="turn">

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!