2013-08-21 50 views
0

,我發現了錯誤未捕獲的ReferenceError:執行的onclick上時未捕獲的ReferenceError:mapCenterAt沒有定義

<script> 
jQuery(document).ready(function ($) { 

    // Map Markers 
    var mapMarkers = [{ 
     address: "217 Summit Boulevard, Birmingham, AL 35243", 
     html: "<strong>Alabama Office</strong><br>217 Summit Boulevard, Birmingham, AL 35243<br><br> 
     <a href='#' onclick='mapCenterAt({latitude: 33.44792, longitude: -86.72963, zoom: 16}, event)'>[+] zoom here</a>", 
     icon: { 
      image: "img/pin.png", 
      iconsize: [48, 48], 
      iconanchor: [48, 48] 
     } 
    }]; 

    // Map Initial Location 
    var initLatitude = 37.09024; 
    var initLongitude = -95.71289; 

    // Map Extended Settings 
    var mapSettings = { 
     controls: { 
      panControl: true, 
      zoomControl: true, 
      mapTypeControl: true, 
      scaleControl: true, 
      streetViewControl: true, 
      overviewMapControl: true 
     }, 
     scrollwheel: false, 
     markers: mapMarkers, 
     latitude: initLatitude, 
     longitude: initLongitude, 
     zoom: 5 
    }; 

    var map = $("#googlemaps").gMap(mapSettings); 

    // Map Center At 
    var mapCenterAt = function(options, e) { 
     e.preventDefault(); 
     $("#googlemaps").gMap("centerAt", options); 
    } 
}); 
</script> 

mapCenterAt是在腳本的底部定義,但:mapCenterAt不與下面的腳本定義錯誤被拋出的頁面。是否需要以不同的方式定義mapCenterAt才能使用onclick?

回答

0

jQuery的文檔就緒處理程序創建了一個不同的作用域,因此mapCenterAt函數不能從內聯onclick處理程序中獲取,因爲它在全局範圍內,這比在文檔就緒範圍內的作用域更高。

你要麼必須使用全局範圍:

window.mapCenterAt = function(options, e) { 
    e.preventDefault(); 
    $("#googlemaps").gMap("centerAt", options); 
} 

,或者創建一個適當的事件處理程序:

<script> 
jQuery(document).ready(function ($) { 
    // Map Markers 
    var mapMarkers = [{ 
     address: "217 Summit Boulevard, Birmingham, AL 35243", 
     html: "<strong>Alabama Office</strong><br>217 Summit Boulevard, Birmingham, AL 35243<br><br><a href='#' id='mapButton'>[+] zoom here</a>", 
     icon: { 
      image: "img/pin.png", 
      iconsize: [48, 48], 
      iconanchor: [48, 48] 
     } 
    }]; 

    // Map Initial Location 
    var initLatitude = 37.09024; 
    var initLongitude = -95.71289; 

    // Map Extended Settings 
    var mapSettings = { 
     controls: { 
      panControl: true, 
      zoomControl: true, 
      mapTypeControl: true, 
      scaleControl: true, 
      streetViewControl: true, 
      overviewMapControl: true 
     }, 
     scrollwheel: false, 
     markers: mapMarkers, 
     latitude: initLatitude, 
     longitude: initLongitude, 
     zoom: 5 
    }; 

    var map = $("#googlemaps").gMap(mapSettings); 

    $(document).on('click', '#mapButton', function(e) { 
     e.preventDefault(); 
     $("#googlemaps").gMap("centerAt", {latitude: 33.44792, longitude: -86.72963, zoom: 16}); 
    }); 
}); 
</script> 
+0

謝謝你這麼多,做的伎倆!將標記答案正確。 –

相關問題