porque_no_les_deux
porque_no_les_deux

Reputation: 479

Creating a variable selector with jQuery?

Let me clarify.

I have a giant loop which parses XML, places markers on a google map accordingly, and makes hidden divs, one per marker, which contain info relating to that marker.

The loop also places on each marker an event which opens an info window. The info window contains a button which must show that particular marker's div.

But I'm uncertain of how to do this. Here is most of the code below-- I have omitted the irrelevant earlier portions of the loop, and focused on the area where I am trying to attach a click event to each new button.

But I am uncertain of how to do this. See the comments in the code for a complete understanding.

$(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);
    });

});

Upvotes: 0

Views: 101

Answers (1)

zerkms
zerkms

Reputation: 254896

First, give the same class to all the buttons

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

Second, bind the event handler to all the mybuttons

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

UPD: as @Felix Kling said - the important thing here is that you need to bind it once, outside the loop

Upvotes: 1

Related Questions