gpt4 book ai didi

javascript - 如何将 Javascript ID 值传递到 window.location.href

转载 作者:行者123 更新时间:2023-12-02 21:05:28 27 4
gpt4 key购买 nike

正在显示纬度和经度,因此我知道脚本正在运行以获取纬度和经度。我的问题是在 window.location.href 中传递 id 值。我得到 [object%20HTMLSpanElement] 作为我的值。这是将我带到“虚拟网站”的 URL https://https://my_website/index.php?category=fast%20food&gps_geo_latitude=[object%20HTMLSpanElement]&gps_geo_longitude=[object%20HTMLSpanElement] 。重点是注意 geo_latitude 和 geo_longitude 的值。我尝试将 .value 添加到变量中,例如: var geo_longitude = document.getElementById('gps_geo_longitude').value;当我这样做时,window.location.href 似乎根本没有执行,并且我的跨度 ID 也没有显示。感谢您的帮助

<body onload="getLocation()">

<span id="gps_geo_longitude"></span>
<span id="gps_geo_latitude"></span>

<script>
var geo_longitude = document.getElementById('gps_geo_longitude');
var geo_latitude = document.getElementById('gps_geo_latitude');

function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
} else {
geo_longitude.innerHTML = "Geolocation is not supported by this browser.";
}
}

function showPosition(position) {

geo_latitude.innerHTML = position.coords.latitude;

geo_longitude.innerHTML = position.coords.longitude;

window.location.href = "https://my_website/index.php?category=fast%20food&gps_geo_latitude=" + gps_geo_latitude + "&gps_geo_longitude=" + gps_geo_longitude;

}

function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
geo_latitude.innerHTML = "User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
geo_latitude.innerHTML = "Location information is unavailable."
break;
case error.TIMEOUT:
geo_latitude.innerHTML = "The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
geo_latitude.innerHTML = "An unknown error occurred."
break;
}
}


</script>
</body>

最佳答案

showPosition() 函数中,您已经将纬度和经度作为 position 传递,您可以像这样直接使用它

function showPosition(position) {
geo_latitude.innerHTML = position.coords.latitude;
geo_longitude.innerHTML = position.coords.longitude;

window.location.href = "https://my_website/index.php?category=fast%20food&gps_geo_latitude=" + position.coords.latitude + "&gps_geo_longitude=" + position.coords.longitude;
}

或者,您可以按照在 span 中设置它们的方式从 DOM 获取它们

function showPosition(position) {
geo_latitude.innerHTML = position.coords.latitude;
geo_longitude.innerHTML = position.coords.longitude;

window.location.href = "https://my_website/index.php?category=fast%20food&gps_geo_latitude=" + geo_latitude.innerHTML + "&gps_geo_longitude=" + geo_longitude.innerHTML;
}

关于javascript - 如何将 Javascript ID 值传递到 window.location.href,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61236780/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com