首页 > 解决方案 > 页面加载时如何做到这一点?

问题描述

我在 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" 的按钮时会发生这一切,但我希望它在页面加载时自动发生,我该怎么做?

标签: javascript

解决方案


只需在块内插入要执行的代码$(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
});

推荐阅读