Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

177
Vistas
¿Cómo hago un seguimiento de varios objetos en Javascript?

Estoy creando una página con varios temporizadores. Los temporizadores se crean cuando un usuario hace clic en un botón. Así que digamos que el usuario hace clic en el botón "K Timer 1". El JS creó un nuevo temporizador al que quiero hacer referencia como "KT1" o temporizadores ['KT1'].

Esta es la forma en que estoy tratando de hacerlo y ustedes, los JS, probablemente se estén riendo de mi solución en este momento. Está bien. Estoy mucho más en casa con PHP.

HTML

 <button type="button" onClick="newUTimer('KT1');"> Timer 1 </button> <button type="button" onClick="newUTimer('KT2');"> Timer 2 </button>

JS - Antiguo con errores

 var timers = {}; newUTimer=function(id){ // If timer does not exist, create it if (!globalThis.timers.[id]){ globalThis.timers.[id] = new CUTimer(id); globalThis.timers.[id].starter(); // If there is already a timer with that ID, reset it }else{ globalThis.timers.[id].reset(); } }

La razón por la que necesito realizar un seguimiento de los temporizadores es para poder restablecer el temporizador cuando un usuario hace clic en el botón por segunda vez en lugar de crear otro temporizador en conflicto.

JS: ACTUALIZADO y en funcionamiento, pero no estoy seguro de que esta sea la forma correcta en que debo hacerlo.

 var timers = {}; newUTimer=function(id){ // If timer does not exist, create it if (!globalThis.timers[id]){ globalThis.timers[id] = new CUTimer(id); globalThis.timers[id].starter(); // If there is already a timer with that ID, reset it }else{ // Call object resetIt method globalThis.timers[id].resetIt(); } }
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Pierda los puntos antes de los corchetes de matriz: globalThis.timers.[id].starter() debe ser globalThis.timers[id].starter()

about 4 years ago · Juan Pablo Isaza Denunciar

0

Debe aceptar la respuesta de aPajos , ya que señaló su error real. En cuanto a la "forma más correcta", deshágase de javascript en línea

 var timers = {}; /*Get the buttons with the data attributes*/ let timerButtons = document.querySelectorAll("button[data-timerid]"); /*Itterate them adding an event handler*/ timerButtons.forEach(function(item){ item.addEventListener("click", function(){ /*Get the id from the data atttribute*/ let timerId = this.dataset.timerid; /*Better to go the positive case first*/ if(timers[timerId]){ timers[timerId].resetIt(); }else{ timers[timerId] = new CUTimer(timerId); } }); }) function CUTimer(id){ this.id = id; this.starter = function(){console.log("Starting : " + this.id)}; this.resetIt = function(){console.log("Resetting : " + this.id)}; //Call your starter method in the construtor this.starter(); };
 <!-- Use Data Attributes to store the timer Id --> <button type="button" data-timerid='KT1'>Timer 1</button> <button type="button" data-timerid='KT2'>Timer 2</button>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda