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

265
Vistas
Loop jQuery script for a list of elements

I have the following jQuery script that I need to execute for a long list of objects.

$("#ID_001").change(function(event) {
    event.preventDefault();
    if(map.hasLayer(ID_001)) {
        $(this).removeClass('selected');
        map.removeLayer(ID_001);
    } else {
        map.addLayer(ID_001);
        $(this).addClass('selected');
   }
});

What I have done

Using the following resource:

  • api.jquery.com
  • jquery-loop-for-script
  • jquery-for-each-looping-a-list-of-objects

I don't think this is a duplicate question of the above as this include an event handler function.

I have written the following loop but this still doesn't work. I can't understand where is the problem.

var obj = {
    "#ID_001": "ID_001",
    "#ID_002": "ID_001"
  };

  $.each( obj, function( key, value ) {
    $(key).change(function(event) {
        event.preventDefault();
        if(map.hasLayer(value)) {
            $(this).removeClass('selected');
            map.removeLayer(value);
        } else {
            map.addLayer(value);
            $(this).addClass('selected');
       }
    });
  });

Can anyone explain to me where is the problem?

Further details

The script is a part of LeafLet map control buttons. Chrome DevTool show this message of error when I click on #ID_001 element, so I think that the problem is that value variable doesn't get the proper value.

Uncaught TypeError: Cannot create property '_leaflet_id' on string 'L_puntiA' at m (Util.js:56) at i.hasLayer (Layer.js:211) at HTMLInputElement. (mymap_main.js:103) at HTMLInputElement.dispatch (jquery-3.3.1.slim.min.js:2) at HTMLInputElement.v.handle (jquery-3.3.1.slim.min.js:2)

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

As sorted out in the comment your problem is that you define the objects with strings instead of variables.

Instead of:

var obj = {
  "#ID_001": "ID_001",
  "#ID_002": "ID_001"
};

Use:

var obj = {
  "#ID_001": ID_001,
  "#ID_002": ID_002
};
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