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

238
Views
¿Cómo puedo configurar elementos ul creados dinámicamente para ingresar un parámetro único en una función?

Usé una función que crea dinámicamente elementos ul con identificadores únicos. Necesito los elementos para poder ejecutar una función y que el código sepa qué elemento ejecutó la función. He escrito un pseudocódigo a continuación para ilustrar:

 <ul id = "topic1" onclick = "getReleventLinks(1)"> element1 </ul> <ul id = "topic2" onclick = "getReleventLinks(2)"> element2 </ul> <ul id = "topic3" onclick = "getReleventLinks(3)"> element3 </ul> getReleventLinks(x){ (gets links with topic x); }

No tengo problemas para incorporar la función al crear estos elementos, pero no puedo encontrar una manera para que el código sepa qué elemento ul ejecutó la función. Solo necesito que se pase la identificación del elemento ul. La función realizará una solicitud xml que devuelve hipervínculos sobre el tema pasado a la función.

Perdón por el pseudocódigo. El código real en su totalidad es bastante grande y sentí que esta era una forma más fácil de explicar el concepto. Sospecho que puede que no sea posible, y también sería bienvenido un método alternativo.

Gracias

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

0

 <ul id="topic1"> element1 </ul> <ul id="topic2"> element2 </ul> <ul id="topic3"> element3 </ul> <script> // First way: // You can query for all elements that have an id that starts with topic // and then add an event listener to each one that can depict which element was clicked // based off the event's currentTarget property. // https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget // Query elements that have a tag name ul and convert the node list // into an array const ulElements = Array.from(document.querySelectorAll('ul')) // Grab only the elements that have an id that starts with topic const elementsWithTopicID = ulElements.filter(element => element.id.startsWith('topic')) function onClick(event) { console.log(event.currentTarget) } // Add the same event listener to each element elementsWithTopicID.forEach(element => element.addEventListener('click', onClick)) // Second Way: // This route is a bit more confusing but much more efficient in my opinion // Add an event listener on the body and use event bubbling to handle the event function onBodyClick(event) { const element = event.target // A return guard to avoid handling elements that do not have ids // that start with topic if (!element.id.startsWith('topic')) return; console.log(element) } // When you add the listener to the body, you can handle all click events // on the children of the body element // https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#event_bubbling_and_capture document.body.addEventListener('click', onBodyClick) </script>
about 4 years ago · Juan Pablo Isaza Report

0

Los clics pasan un objeto de event a las funciones que manejan ese evento. Ese objeto de evento tiene una propiedad de target que es el elemento HTML que activó ese evento.

Pero para usar eso, no puede pasar sus funciones como cadenas. No deberías de todos modos, es una mala práctica. En su lugar, vincule los controladores de clic a los elementos y pase una referencia a una función como controlador. Luego se llamará a la función con el evento como primer argumento.

Ejemplo de trabajo:

 function getReleventLinks(event){ console.log(event.target.id) } // 'ul' here is whatever CSS selector targets your list document.querySelectorAll('ul').forEach(ul => { ul.addEventListener('click', getReleventLinks); })
 <ul id = "topic1"> element1 </ul> <ul id = "topic2"> element2 </ul> <ul id = "topic3"> element3 </ul>

about 4 years ago · Juan Pablo Isaza Report

0

Puede usar una función para todos ellos, sin pasar la identificación, solo use this palabra clave y obtenga la identificación del elemento para su xmlrequest

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!