我在index page
中有一堆标记,我在循环中创建并注册侦听器。我点击其中一个标记,然后我转到next page
,我有一个anchor button
,需要知道哪个标记启动了该操作。我有一个明智的步骤:
//outputs a correct id 1 in console
//outputs a correct id 1 in console on clicking anchor
//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
});
});
});
答案 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'));
});