我试图获取用户当前的城市以及单击时通过 getCity 函数传递的任何参数,但我的“x”变量未定义。这是代码..
<button onclick="getCity('burger')">burger</button>
<button onclick="getCity('steak')">steak</button>
<button onclick="getCity('taco')">taco</button>
<script type="text/javascript">
//get city
function getCity(x) {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPos);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
//get lat and long
function showPos(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
//get address
var geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({
'location': latlng
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
//get city
if (results[0]) {
var city = results[0]['address_components'][2].long_name;
var x = x;
alert(x +" "+ city); // i'm getting undefined + currentcity
}
}
});
}
</script>
我得到了未定义+当前城市。如果我点击汉堡按钮,我该如何制作才能获得汉堡+当前城市?
最佳答案
你倒数第二句话
var x = x;
将未定义的 x 分配给 x。两个“x”均未定义。
关于javascript 参数不通过函数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34804038/