我对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.";
}
}
答案 0 :(得分:1)
只需定义一个location
,然后使用.add-button
将单个侦听器添加到一个querySelector
:
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.";
}
});