Google地图v3中循环中的标记侦听器

时间:2013-07-19 21:18:54

标签: javascript jquery jquery-mobile google-maps-api-3 javascript-events

我在index page中有一堆标记,我在循环中创建并注册侦听器。我点击其中一个标记,然后我转到next page,我有一个anchor button,需要知道哪个标记启动了该操作。我有一个明智的步骤:

  • 点击标记1 //outputs a correct id 1 in console
  • 转到下一页//outputs a correct id 1 in console on clicking anchor
  • 返回索引页面并点击标记2 //outputs a correct id 2 in console
  • 转到下一页//outputs both ids 1 and 2 in console on clicking anchor

最后一步是问题出在哪里我只想id 2。事实上,如果我第三次重复这个过程,我会得到所有id 1,2和3,而在这种情况下我只想要id 3

我的代码:

$.each(otherLocations, function(index, value){
  var markerOtherLocations = new MarkerWithLabel({
    position: new google.maps.LatLng(value.latitude, value.longitude),
    map: map,
    title: value.name+" "+value.distance,
    icon: iconImage,
    labelContent: value.name+" "+value.distance,
    labelAnchor: new google.maps.Point(50, 0),
    labelClass: "labels", // the CSS class for the label
    labelStyle: {opacity: 0.60}
  });


  google.maps.event.addListener(markerOtherLocations, 'click', function() {
    $.mobile.changePage("#detail-page", { transition: "flip"} );
    console.log(value.localurl);//Outputs correct url

    $("#ref").on("click", function(){  //The problem is in this anchor click
      console.log(value.localurl);//Outputs the current as well as all the previous urls
    });
  });
});

1 个答案:

答案 0 :(得分:1)

每次点击markerOtherLocations时,它都会为onclick注册一个全新的#ref事件回调,从而导致问题。请记住,事件可以通过许多回调注册。请考虑以下代码:

$("#ref").on("click", function(){  
  console.log('do function A');//register A first
});

$("#ref").on("click", function(){ 
  console.log('do function B');//register B later, which won't be overridden.
});

//If you click #ref then, it'll output A and B, following the registered sequence before.

所以在我看来,你的代码可能是:

google.maps.event.addListener(markerOtherLocations, 'click', function() {
  $.mobile.changePage("#detail-page", { transition: "flip"} );
  console.log(value.localurl);//Outputs correct url
  $("#ref").data('origin',value.localurl);
});

$("#ref").on("click", function(){ // register once 
  console.log($(this).data('origin'));
});