0

我有这个代码:

siteCheckboxes.each(function () {

        var lat = $(this).attr("lat");
        var lng = $(this).attr("lng");
        var myLatlng = new google.maps.LatLng(lat, lng);
        var marker = new google.maps.Marker({ icon: smallDotIcon, position: myLatlng, map: map, title: $(this).attr("siteName") });
        var $checkbox = $(this);
        $(this).click(function () {
            if ($(this).attr("checked")) {

              marker.setIcon(null);  
            } else {
               marker.setIcon(smallDotIcon);

            }

        });
        google.maps.event.addListener(marker, 'click', function () {
              $checkbox.click();
        });


    });

这个想法是我有几个带有站点名称的复选框和一个带有小点的地图,用于地图上的每个站点。当用户选中站点复选框时,地图上的标记应更改为完整标记。这部分应用程序工作正常。

当用户点击一个标记时,相关复选框的状态应该会改变,标记的形状也会改变,但它不起作用。

当用户单击标记时,复选框选中状态和标记形状不同步。问题是什么?

一些调试告诉我,如果用户单击标记,则调用标记的单击事件,并且还会调用相关复选框的单击事件,但是选中状态会在复选框单击事件完成后发生变化。

为什么点击事件结束后它会改变?

4

1 回答 1

0

The problem is that you're looping over all your checkboxes, creating your click handlers. However when the user then clicks on any marker, it will always use the last value for $checkbox, not the one corresponding with when you created the marker eventlistener.

You need a closure.

Try something like this instead. Create a new top-level function, bindClick, outwith your .each loop. In your .each loop, call that function. This then creates the event listener with whatever checkbox you're looping over at the time.

siteCheckboxes.each(function () {
    var lat = $(this).attr("lat");
    var lng = $(this).attr("lng");
    var myLatlng = new google.maps.LatLng(lat, lng);
    var marker = new google.maps.Marker({ icon: smallDotIcon, position: myLatlng, map: map, title: $(this).attr("siteName") });
    var $checkbox = $(this);


    bindClick($checkbox, marker);
});


function bindClick(checkbox, marker) {
    google.maps.event.addListener(marker, 'click', function () {
          checkbox.click();
    });
}
于 2012-09-04T09:12:37.080 回答