/ / Créer un sélecteur de variable avec jQuery? - jquery

Créer un sélecteur de variable avec jQuery? - jquery

Laissez-moi clarifier.

J'ai une boucle géante qui analyse XML, place les marqueurs sur une carte Google en conséquence et crée des divs cachés, un par marqueur, contenant des informations relatives à ce marqueur.

La boucle place également sur chaque marqueur un événement qui ouvre une fenêtre d’informations. La fenêtre d’information contient un bouton qui doit montrer ce marqueur "s div.

Mais je ne sais pas comment faire cela. Voici la majeure partie du code ci-dessous - j'ai omis les parties antérieures non pertinentes de la boucle et je me suis concentré sur la zone où j'essaie d'attacher un événement de clic à chaque nouveau bouton.

Mais je ne sais pas comment faire cela. Voir les commentaires dans le code pour une compréhension complète.

$(xml).find("sample").each(function () {

var id = $(this).find("id long").text();

/*there was code here which creates the other variables you see below*/

var infoPage = "<div style="display:none; position:absolute; top:0px; bottom:0px; width:100%;" id="" + id + "Info">" + "<p>Number: " + number + "</p>" + "<p>ID: " + id + "</p>" + "<p>Rock type: " + rockType + "</p>" + "<p>Minerals: " + minerals + "</p>" + "<p>Regions: " + regions + "</p>" + "<p>Latitude: " + latitude + "</p>" + "<p>Longitude: " + longitude + "</p>" + "</div>";

//there was code here which inserts this div into the page

//this line creates the button which appears inside the info window
var contentString = "<a href="" data-role="button" id="" + id + "">" + number + "</a>";

//this line creates the info window
var infowindow = new google.maps.InfoWindow({
content: contentString
});

/*Here is where I hit a problem. I now need to construct a line of jQuery which attaches to this particular button a click event. But it needs to do it for every new button in the loop, so that each button"s click event is unique and opens its personal div. How do I construct a selector which will change with the loop to accomplish the desired result?*/
$("#" + id).click(function () {
$("#" + id + "Info").show();
});

google.maps.event.addListener(marker, "click", function () {
infowindow.open(map, marker);
});

});

Réponses:

1 pour la réponse № 1

D'abord, donnez la même classe à tous les boutons

var contentString = "<a href="" class="mybutton" data-role="button" id="" + id + "">" + number + "</a>";

Deuxièmement, liez le gestionnaire d’événements à tous les mybuttons

$(document).on("click", ".mybutton", function() {
$("#" + $(this).attr("id") + "Info").show();
});

UPD: comme @Felix Kling a dit - la chose importante ici est que vous devez le lier une fois, en dehors de la boucle