0

我明白为什么它不起作用。但不知道如何得到结果:

有一个全局数组:

var members=[[1,x,y,z],[2,x1,y1,z1],[3,x2,y2,z3]];

function drop() {
  for (var i = 0; i < members.length-1; i++) { 
    setTimeout(function() {
      addMarker();
    }, i * 30);
  }
}

function addMarker() { 
  var marker = new google.maps.Marker({
    position: members[iterator][1],
    icon: pinImage[members[iterator][2]],
    shadow: shadow,
    map: map,
    draggable: false,
    title: members[iterator][3],
    animation: google.maps.Animation.DROP    }); 
  google.maps.event.addListener(marker, 'click', function() {
    $.ajax({
      url : 'ajax/get_infowindow_content.php?id='+members[iterator][0],
      success: function(data) {
        infowindow.close();
        infowindow.setContent(data);
        infowindow.open(map, marker);
      }
    });
  }); 
  markers.push(marker);  
  iterator++;
}

问题在这里:

url : 'ajax/get_infowindow_content.php?id='+members[iterator][0],

当我单击标记时,它会触发函数并检查 members[iterator][0] 但迭代器是迭代器的最后一个值(在整个循环之后)。

最好的解决方案是某种 .value() ,例如:

url : 'ajax/get_infowindow_content.php?id='+members[iterator][0].value(),

但当然它不起作用。

我堆了。。

4

2 回答 2

2

您只需要一个闭包并将参数传递给 addMarker 函数:

var members = [[1, x, y, z], [2, x1, y1, z1], [3, x2, y2, z3]];

function drop() {
    for (var i = 0; i < members.length; i++) {
        (function(j) {
            setTimeout(function() {
                addMarker(members[j]); //pass the value
            }, i * 30);
        })(i); //closure to keep the value
    }
}

function addMarker(member) {
    var marker = new google.maps.Marker({
        position: member[1],
        icon: pinImage[member[2]],
        shadow: shadow,
        map: map,
        draggable: false,
        title: member[3],
        animation: google.maps.Animation.DROP
    });
    google.maps.event.addListener(marker, 'click', function() {
        $.ajax({
            url: 'ajax/get_infowindow_content.php?id=' + member[0],
            success: function(data) {
                infowindow.close();
                infowindow.setContent(data);
                infowindow.open(map, marker);
            }
        });
    });
    markers.push(marker);
}​
于 2012-12-15T17:10:37.713 回答
0

尝试i作为参数传递addMarker()

function addMarker(i){/* code*/}

然后在循环中:

setTimeout(function() {
      addMarker(i);
    }, i * 30);
于 2012-12-15T17:11:34.260 回答