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

139
Views
Haga clic en el comando con un detector de eventos en lugar de un evento onclick

Estoy trabajando en un problema simple que me pidió que agregara un comando onclick y activara la función. Lo hice, pero ahora quiero ver si puedo hacerlo con un evenListener. Resulta que no puedo. ¿alguien puede decirme que estoy haciendo mal?

 <body> <p><a id="w3r" type="text/html" hreflang="en-us" rel="nofollow" target="_self" href="https://www.w3resource.com/">w3resource</a></p> <button >Click here to get attributes value</button> </body></html> function getAttributes() { var v = document.getElementById('w3r').href ; alert('the value of the attrbibute is : '+v); var w = document.getElementById('w3r').hreflang; alert('the value of the attrbibute is : '+w); var x = document.getElementById('w3r').rel; alert('the value of the attrbibute is : '+x); var y = document.getElementById('w3r').target; alert('the value of the attrbibute is : '+y); var z = document.getElementById('w3r').type; alert('the value of the attrbibute is : '+z); document.getElementsByTagName('P')[0].addEventListener('click' , getAttributes()); }
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

  1. Puede encontrar querySelector más fácil de usar.

  2. getAttributes() asigna el resultado de llamar a la función al oyente en lugar de asignar la referencia a la función que se llamará cuando se active el oyente: addEventListener('click', getAttributes); .

  3. Su oyente está dentro de la función. Debe estar fuera de la función, de lo contrario nunca será llamado.

  4. Parece que desea que el detector de clics esté en el botón, y no en el elemento de párrafo.

  5. Puede ahorrar en la repetición iterando sobre los atributos del elemento .

 function getAttributes() { const el = document.querySelector('#w3r'); if (el.hasAttributes()) { Array.from(el.attributes).forEach(attr => { console.log(`The value of ${attr.name} is ${attr.value}`); }); } } const button = document.querySelector('button'); button.addEventListener('click', getAttributes);
 <p><a id="w3r" type="text/html" hreflang="en-us" rel="nofollow" target="_self" href="https://www.w3resource.com/">w3resource</a></p> <button>Click here to get attributes value</button>

Documentación adicional

  • Array.from

  • Plantilla/literales de cadena

about 4 years ago · Juan Pablo Isaza Report

0

Primero, eventListener está dentro de la función. Segundo en getElementsByTagName pones P (mayúsculas), eso funciona si pones p (minúsculas)

about 4 years ago · Juan Pablo Isaza Report

0

El error es que está agregando un detector de eventos en una función que está tratando de llamar. Entonces, esto significa que no se agregará a su elemento hasta que se llame desde otro lugar (lo que nunca sucederá en su caso). La solución para esto es poner la línea donde agrega el detector de eventos directamente en la etiqueta del script

 document.getElementsByTagName('P')[0].addEventListener('click' , getAttributes());

Solo asegúrese de que su secuencia de comandos esté al final del body y no en la head o al principio porque la página se carga de arriba a abajo y si coloca su secuencia de comandos sobre su html, no podrá obtener su elemento ya que no lo hará. existe todavía en el tiempo que intenta conseguirlo.

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!