如何重构获取用户当前位置的 JS 代码?

How can I refactor this JS code that fetches a user's current location?

我不是最擅长 JS 的,我有这段代码可以使用地理位置 api 获取用户的当前坐标。最初它需要使用许多不同的按钮,但现在只有一个按钮,因此无需遍历数组。我如何重构此代码以反映这一点?

var locations = ["coordinatesStore"]
  .map(id => document.getElementById(id));

Array.prototype.forEach.call(
  document.querySelectorAll('.add-button'),
  (button, i) => {
    button.addEventListener('click', () => getLocation(i));
  }
);

function getLocation(i) {
  var location = locations[i];
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(({ coords: { latitude, longitude }}) => {
      location.value = latitude + ", " + longitude;
    });
  } else { 
    location.value = "Geolocation is not supported by this browser.";
  }
}

只需定义一个 location,并使用 querySelector:

.add-button 添加一个监听器
const location = document.getElementById('coordinatesStore');
document.querySelector('.add-button').addEventListener('click', () => {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(({ coords: { latitude, longitude }}) => {
      location.value = latitude + ", " + longitude;
    });
  } else { 
    location.value = "Geolocation is not supported by this browser.";
  }
});