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

167
Views
¿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 answers
Answer question

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 Report

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 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!