链接OpenStreetMap API到网站时未捕获的TypeError



我的结帐页面的前端有一个woocommerce形式的几个字段,我试图链接到OpenStreetMap API作为一个插件。然而,在加载.js脚本并激活插件后,每当我加载结帐页面时,我都会得到一个

Uncaught TypeError: Uncaught TypeError: Cannot set property of null(设置'onclick')at geocoding.js?ver=1.0:8:26

消息。下面是我使用的代码:

// Get the Place Order button
var placeOrderButton = document.getElementById('place_order');
// Check if script has been loaded successfully
console.log('Geocoding script loaded.');
// Add an event listener to the button
placeOrderButton.onclick = function() {
// Get the form data
var formData = {
country: document.querySelector('input[name="billing_country"]').value,
street: document.querySelector('input[name="billing_address_1"]').value,
city: document.querySelector('input[name="billing_city"]').value,
county: document.querySelector('input[name="billing_state"]').value,
};
// Construct the URL with the form data
var url = 'https://nominatim.openstreetmap.org/search?' + 'q=' + formData.street + ', ' + formData.city + ', ' + formData.county + ', ' + formData.country + '&format=json';
// Send the API request
fetch(url)
.then(response => response.json())
.then(data => {
// Get the latitude and longitude values from the response
var lat = data[0].lat;
var lon = data[0].lon;
// Do something with the latitude and longitude values
console.log('Latitude: ' + lat);
console.log('Longitude: ' + lon);
})
.catch(error => {
// Log any errors that occur
console.error('Error:', error);
});
};

错误语句突出显示了"function() {"代码的一部分。我已经尝试使用字段名称以及安装第三方结帐页面管理器来获取元素ID,但错误仍然存在。我哪里做错了

期望的输出是浏览器开发人员工具的控制台选项卡中的纬度和经度坐标。我怀疑这可能是一个问题,不正确的定位woocommerce结帐表单元素。因此,如果你可能有一个想法如何获得实际的woocommerce checkout表单元素id,我认为它应该有所帮助。

从错误消息中可以明显看出,当您尝试为其onclick属性赋值时,placeOrderButton为null。在document.getElementById('place_order');中使用的id是错误的,或者在执行时元素还没有出现在DOM中。

也许插件有一些机制来提醒你什么时候完成加载,你必须等待这发生之前,试图添加onclick侦听器(提供的问题是插件生成按钮,你试图查找它太快)。

最新更新