1
由於某些原因,同一腳本標記中的代碼運行良好,但調用包含與其他腳本標記相同的代碼的函數不會。在腳本標記內的其他地方調用函數不起作用
在我的代碼中,我在頭文件中有一個谷歌地圖腳本,它工作得很好,我們稱之爲腳本標記(A)。
問題是,當我不在腳本標記A中,並且想從另一個腳本標記中調用腳本A中的函數來重用它時。不起作用。但是,如果我從該函數複製代碼並將其直接放在同一個標記中,它將起作用。
我希望能夠調用它不要再寫一次。我的代碼中有什麼錯誤?
的完整代碼:
<html>
<head runat="server">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script
src="http://maps.googleapis.com/maps/api/js">
</script>
<script>
//this is the function that I want call
function getAddress(location) {
var geocoder = new google.maps.Geocoder();
var latLng = new google.maps.LatLng(location.lat(), location.lng());
geocoder.geocode({
latLng: latLng
},
function (responses) {
if (responses && responses.length > 0) {
$("#addressResult").text(responses[0].formatted_address);
// alert(responses[0].formatted_address);
} else {
alert('Cannot determine address at this location.');
}
});
}
var map;
var myCenter = new google.maps.LatLng(51.508742, -0.120850);
function initialize() {
var mapProp = {
center: myCenter,
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
google.maps.event.addListener(map, 'click', function (event) {
placeMarker(event.latLng);
});
}
var marker
function placeMarker(location) {
if (marker) {
marker.setPosition(location);
} else {
marker = new google.maps.Marker({
position: location,
map: map
});
}
//calling it inside and it's working
getAddress(location);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<label>Location: </label>
<label id="addressResult"></label>
<input type="button" value="Current Location" onclick="getLocation()" />
<script>
var x = document.getElementById("addressResult");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
//here where I want to call it
getAddress(position);
}
</script>
<div id="googleMap" style="width: 500px; height: 380px;"></div>
<div>
</body>
</html>
確保你的第二個腳本塊是ID'的元素之後addressResult'。更好的是,把所有東西都放在頭上,並使用適當的onload處理。 –
將來請提供一個完整的測試用例(現在不清楚這些'