我是 Ruby on Rails 的实习生,昨天我不得不用 Javascript 做一些事情(我的 javascript 技能很糟糕,我什至没有这方面的技能)。
我在一个项目中实现了当前位置功能,但我想用另一种方式来做......事情已经完成了,看一下:
function geolocationSuccess(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var geocoder = new google.maps.Geocoder();
var latlng = {lat: latitude, lng: longitude};
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
if (results[0]){
var user_address = results[0].formatted_address;
document.getElementById("current_location").innerHTML = user_address;
}else {
console.log('No results found for these coords.');
}
}else {
console.log('Geocoder failed due to: ' + status);
}
});
}
function geolocationError() {
console.log("please enable location for this feature to work!");
}
$(document).on("ready page:ready", function() {
$("#current-location").on("click", function(event) {
event.preventDefault();
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition(geolocationSuccess, geolocationError);
} else {
alert("Geolocation not supported!");
}
});
});
好吧,我知道当我点击 Id="current-location"按钮时这一切都会发生,但我希望它在页面加载时自动发生,我该怎么做?
最佳答案
只需将要执行的代码插入到 $(document).ready(
block 中即可:
$(document).ready(function() {
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition(geolocationSuccess, geolocationError);
} else {
alert("Geolocation not supported!");
}
});
顺便说一句,我建议不要命名函数变量event
,因为event是一个关键字。将事件传递给函数的标准约定是使用e
。例如:
$('#someId').on('click', function(e) {
e.preventDefault();
//do something
});
关于javascript - 当页面加载时我怎样才能做到这一点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56508371/