用jQuery创建变量选择器?

时间:2012-05-28 02:09:24

标签: jquery

让我澄清一下。

我有一个解析XML的巨型循环,相应地在谷歌地图上放置标记,并制作隐藏的div,每个标记一个,其中包含与该标记相关的信息。

循环还会在每个标记上放置一个打开信息窗口的事件。信息窗口包含一个按钮,该按钮必须显示特定标记的div。

但我不确定如何做到这一点。以下是大部分代码 - 我省略了循环中不相关的早期部分,并专注于我尝试将click事件附加到每个新按钮的区域。

但我不确定如何做到这一点。请参阅代码中的注释以获得完整的理解。

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

});

1 个答案:

答案 0 :(得分:1)

首先,为所有按钮提供相同的类

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

其次,将事件处理程序绑定到所有mybuttons

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

UPD :正如@Felix Kling所说 - 重要的是你需要在循环之外绑定它一次