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

181
Views
"cambiar contenido al hacer clic" en la función javascript cada clic

hola, solo quiero hacer el botón en html cuando hace clic, el resultado del contenido de cada función podría cambiar con cada nombre de función. pero en este mi código, lamentablemente no cambia. y solo aparece como resultado de la función 3, y cuando hago clic en segundo y tercero y esto no cambia en absoluto.

 <!DOCTYPE html> <html> <body> <h1>HTML DOM Events</h1> <h2>The onclick Event</h2> <p>The onclick event triggers a function when an element is clicked on.</p> <p>Click to trigger a function that will output "Hello World":</p> <button onclick="myFunction(),myFunction2(),myFunction3()">Click me</button> <p id="demo"></p> <script> function myFunction() { document.getElementById("demo").innerHTML = "Hello World"; } function myFunction2() { document.getElementById("demo").innerHTML = "Hello lllo"; } function myFunction3() { document.getElementById("demo").innerHTML = "Hello ok"; } </script> </body> </html>

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

0

Si desea ejecutar las tres funciones con un evento de clic, debe usar AddEventListener para el evento de clic en lugar del evento de clic nativo.

 <!DOCTYPE html> <html> <body> <h1>HTML DOM Events</h1> <h2>The onclick Event</h2> <p>The onclick event triggers a function when an element is clicked on.</p> <p>Click to trigger a function that will output "Hello World":</p> <button id="button">Click me</button> <p id="demo"></p> <script> const button = document.getElementById('button'); button.addEventListener('click', myFunction) button.addEventListener('click', myFunction2) button.addEventListener('click', myFunction3) function myFunction() { document.getElementById("demo").innerText += "Hello World"; } function myFunction2() { document.getElementById("demo").innerText += "Hello lllo"; } function myFunction3() { document.getElementById("demo").innerText += "Hello ok"; } </script> </body> </html>

O agrega un detector de eventos y ejecuta las tres funciones internas.

 button.addEventListener('click', () => { myFunction() myFunction2() myFunction3() })

Y si desea concatenar el texto con el último valor del texto interno del elemento de demostración, debe usar "+=" en lugar de "="

about 4 years ago · Juan Pablo Isaza Report

0

Como no queda muy claro a partir de la pregunta en sí qué está tratando de lograr, solo voy a suponer que desea activar función por función. Entonces, la función se ejecuta básicamente una por una... Así:

 <!DOCTYPE html> <html> <body> <h1>HTML DOM Events</h1> <h2>The onclick Event</h2> <p>The onclick event triggers a function when an element is clicked on.</p> <p>Click to trigger a function that will output "Hello World":</p> <button onclick="alertFirst(), alertSecond()">Click me</button> <p id="demo"></p> <script> var el = document.getElementById('demo'); // create named functions: //Instead of alert, you will want to set innerhtml, so just change that function alertFirst() { alert('hello world'); }; function alertSecond() { alert('hello 2 world'); }; // assign functions to the event listeners (recommended): el.addEventListener('click', alertFirst); el.addEventListener('click', alertSecond); // then you could remove either one of the functions using: el.removeEventListener('click', alertFirst); el.removeEventListener('click1', alertSecond); </script> </body> </html>

about 4 years ago · Juan Pablo Isaza Report

0

Por lo general , no es una buena idea usar controladores de eventos en línea.

Puede usar addEventListener para 'escuchar' ciertos eventos en un elemento y manejar dichos eventos. Más genérico, es posible usar un controlador para todos los elementos en un documento. Este último se denomina delegación de eventos .

El fragmento demuestra ambas estrategias.

 // single element click event listeners document.querySelector(`#demoBttn1`).addEventListener(`click`, handleClick); document.querySelector(`#demoBttn2`).addEventListener(`click`, handleClick2); // generic (delegated) click event listener document.addEventListener(`click`, handleAllClicks); // single element handler (#demoBttn1) function handleClick(evt) { document.querySelector(`#demo`) .insertAdjacentHTML(`beforeend`, `<div>Hello Wrld</div>`); } // single element handler (#demoBttn2) function handleClick2(evt) { document.querySelector(`#demo`) .insertAdjacentHTML(`beforeend`, `<div>Hello you</div>`); } // delegate handler function handleAllClicks(evt) { if (evt.target.id.startsWith(`demoAll`)) { return document.querySelector(`#demo`) .insertAdjacentHTML(`beforeend`, `<div>${ evt.target.dataset.text2add}</div>`); } if (evt.target.id === `demoCombined`) { return document.querySelectorAll(`[data-text2add]`) .forEach(bttn => bttn.click()); } if (evt.target.id === `clear`) { return document.querySelector(`#demo`).textContent = ``; } }
 <p> <button id="demoBttn1">hello</button> <button id="demoBttn2">hello you</button> (single button handling) </p> <p> <!-- the data attribute value will be used for the text to add to p#demo --> <button id="demoAll1" data-text2add="Hi there">say hi</button> <button id="demoAll2" data-text2add="Hello there">say hello</button> <button id="demoAll3" data-text2add="Goodbye">say bye</button> <button id="demoCombined" >hi, hello and bye</button> (delegated) </p> <p> <button id="clear">clear all</button> (delegated) </p> <p id="demo"></p>

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!