gpt4 book ai didi

javascript - 如何将以下内容绑定(bind)到按钮单击事件上的本地 this 上下文变量?

转载 作者:行者123 更新时间:2023-12-03 09:28:12 24 4
gpt4 key购买 nike

我真的需要这方面的帮助。如何使用按钮单击事件打印纬度和经度,例如:

<button id="geo" onclick="OnGeoClick()"> Get Location </button>

我有以下代码:

var getGeo = {
showPosition :
function showPosition(position) {
self = this;
console.log(self)
self.lat = position.coords.latitude;
self.lng = position.coords.longitude;
console.log(self);
},


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

getLocation :
function getLocation() {
self = this;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(self.showPosition, self.showError, {enableHighAccuracy:true});
console.log(self);
} else {
self.err = "Geolocation is not supported by this browser.";}
}
};

function OnGeoClick() {...local this context binding?...}

这样窗口不存储纬度和经度,而是一个可以记录(结果)的可访问变量;

最佳答案

您可以使用绑定(bind)方法来保持上下文完整。

navigator.geolocation.getCurrentPosition(self.showPosition.bind(self), self.showError, {enableHighAccuracy:true});

这样调用它

function OnGeoClick() { 
getGeo.getLocation();
}

关于javascript - 如何将以下内容绑定(bind)到按钮单击事件上的本地 this 上下文变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31597563/

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