2014-06-22 2 views
0

2 초마다 마커를 업데이트하는지도가 있습니다. 제 3 자 라이브러리를 사용하여 토스트 메시지를 보여줍니다. 특정 마커에서 '무언가'가 잘못되었습니다. 토스트를 클릭하면지도가 중앙에 오르고 특정 마커로 확대되기를 원합니다.자바 스크립트 : 클릭 이벤트를 루프로 지정

하나의 마커는 모두 정상적으로 작동하지만 토스트가 여러 개인 경우 마지막 마커 ('무언가'가 잘못 되었음)가 모두 표시됩니다. 이 문제는 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

루프에 'j'iterator를 사용하지 않고 onclick 이벤트를 수행합니다. toastr.options가 배열 요소라면 toastr.options [j] – webkit

답변

0

당신은 자바 스크립트 클로저는이 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]); 
관련 문제