javascript - 页面加载时如何做到这一点?
问题描述
我在 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(
:
$(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
});
推荐阅读
- angular - 如何使子路由在 AngularDart 中工作?
- reactjs - useState() 没有从事件处理程序更新状态?
- julia - 有没有办法在 Julia 中强制使用隐藏的默认构造函数?
- ruby-on-rails - Rails:通过belongs_to查询has_one在查询中添加PK null
- python - 来自 XYZ csv 格式的栅格
- dynatrace - 来自 Dynatrace 的 /etc/passwd(或任何 xyz 文件)文件更改警报
- sql-server - 我可以根据全新 proc 中的 Column 对多个存储过程进行分组吗?避免重复结果?
- javascript - 香草javascript中的下拉过滤器
- windows - 使用批处理文件变量值扩展路径注册表项值的正确语法
- swift - 如何在 SwiftUI 中删除列表的左右填充?