2014-06-22 26 views
0

我有一張每兩秒更新其標記的地圖。我使用第三方庫顯示敬酒信息,該信息庫在特定標記處「某些」有誤。當點擊烤麪包片時,我想讓地圖居中並放大到特定的標記。Javascript:分配循環中的點擊事件

這一切都適用於單個標記,但是當我有多個敬酒時,它們最終都會顯示最後一個標記(哪裏出現錯誤)。 我知道這是一個與js關閉和範圍有關的問題,但我無法找出解決方法。

if(/*something is wrong at marker*/) { 
    if(toastShown.indexOf(i) == (-1)) // check if toast has been shown 
    { 
     toastShown.push(i);  // mark toast for current marker as shown 
     var err = "Problem detected! Click to go to location"; 
     toastr.error(err, 'Error!', {timeOut: 10000}); 
     problemAtPoint.push(point); 
     index++; 
    }  
} 

for(var j = 0; j < index; j++) { 
    toastr.options.onclick = (function() { 
     return function() { 
      //alert('clicked!'); 
      map.setCenter(problemAtPoint[index]); 
      map.setZoom(15); 
     } 
    })(problemAtPoint[index]); 
} 
+0

在您的循環中添加一個onclick事件,而不使用'j'迭代器..所以如果toastr.options是你的元素數組,它應該是toastr.options [j] – webkit

回答

0

你必須考慮什麼的Javascript閉包,看看這個https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures

jsfiddle 顯示了使用循環

function setupHelp() { 
    var helpText = [ 
     {'id': 'email', 'help': 'Your e-mail address'}, 
     {'id': 'name', 'help': 'Your full name'}, 
     {'id': 'age', 'help': 'Your age (you must be over 16)'} 
    ]; 

    for (var i = 0; i < helpText.length; i++) { 
     var item = helpText[i]; 
     document.getElementById(item.id).onfocus = makeHelpCallback(item.help); 
    } 
} 

您的問題,似乎你不使用封閉的例子參數

toastr.options.onclick = 
    (function(ITEM) { 
     return function() { 
      //alert('clicked!'); 
      map.setCenter(ITEM); 
      map.setZoom(15); 
     } 
})(problemAtPoint[index]);