JavaScript选择器失效:行程计算结果无法正确显示求助
问题分析与修复方案
核心问题点
- 重复ID违反HTML规范:三个服务区块都使用了
ride-price、distance、duration这些相同ID,浏览器无法精准定位每个区块内的元素,导致计算结果无法渲染到对应位置。 - 区块默认隐藏:所有服务区块都带有
hidden类,就算计算完成,内容也不会显示在页面上。 - 代码逻辑错误:
- 重复定义
distance变量,存在冗余 - 配送服务错误使用了经典车型的价格,应该用固定配送费
- 直接替换标题的innerHTML会覆盖原有DOM结构,导致内部元素被破坏
- 重复定义
修复步骤与修正代码
1. 修正HTML结构(保证ID唯一)
给每个区块内的元素ID加上专属前缀,避免冲突:
<div class="about-section"> <div id="executive-ride" class="about-section-1 hidden"> <div class="about-section-title"> Executive Ride: <strong id="executive-ride-price">₦NaN</strong> / <span id="executive-distance"></span> km / <span class="black-text" id="executive-duration"></span> <div id="executive-total-price"></div> <div class="about-section-more"> NOTE: This is an approximate estimate. Actual cost may vary according to the traffic. </div> </div> </div> <div id="classic-ride" class="about-section-2 hidden"> <div class="about-section-title"> Classic Ride: <strong id="classic-ride-price">₦NaN</strong> / <span id="classic-distance"></span> km / <span class="black-text" id="classic-duration"></span> <div id="classic-total-price"></div> <div class="about-section-more"> NOTE: This is an approximate estimate. Actual cost may vary according to the traffic. </div> </div> </div> <div id="service-delivery" class="about-section-3 hidden"> <div class="about-section-title"> Service Delivery: <strong id="delivery-ride-price">₦NaN</strong> / <span id="delivery-distance"></span> km / <span class="black-text" id="delivery-duration"></span> <div id="delivery-total-price"></div> <div class="about-section-more"> NOTE: This is an approximate estimate. Actual cost may vary according to the traffic. </div> </div> </div> </div>
2. 优化JavaScript逻辑
移除冗余代码,修正价格错误,精准更新元素内容,并在计算完成后移除隐藏类:
// Set up the map and geocoder objects var map; var geocoder; // Get the user's current location and set it as the starting point function getCurrentLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { var latlng = { lat: position.coords.latitude, lng: position.coords.longitude }; geocoder.geocode({ 'location': latlng }, function(results, status) { if (status === 'OK') { if (results[0]) { // Set the origin field in the mapping API document.getElementById('origin').value = results[0].formatted_address; } else { alert('No results found'); } } else { alert('Geocoder failed due to: ' + status); } }); }, function() { alert('Unable to retrieve your location'); }); } else { alert('Geolocation is not supported by this browser.'); } } // Get the input fields for the origin and destination const originInput = document.getElementById("origin-input"); const destinationInput = document.getElementById("destination-input"); // Create a new Google Maps Distance Matrix service const distanceService = new google.maps.DistanceMatrixService(); // When the user selects a destination, calculate the distance and display it destinationInput.addEventListener("change", function() { const origin = originInput.value; const destination = destinationInput.value; // Call the Distance Matrix API to calculate the distance distanceService.getDistanceMatrix({ origins: [origin], destinations: [destination], travelMode: google.maps.TravelMode.DRIVING, unitSystem: google.maps.UnitSystem.METRIC, }, function(response, status) { if (status === "OK") { // Validate response structure if (!response?.rows?.length || !response.rows[0]?.elements?.length || !response.rows[0].elements[0].distance) { console.log('Error: Invalid API response'); return; } // Get the distance and duration from the response const distance = response.rows[0].elements[0].distance.value / 1000; // Convert to km const duration = response.rows[0].elements[0].duration.text; // Calculate the ride price based on the distance const pricePerKmExecutive = 20; // Pricing: ₦20 per kilometer for executive ride const pricePerKmClassic = 10; // Pricing: ₦10 per kilometer for classic ride const deliveryPrice = 15; // Flat delivery fee: ₦15 const executiveRidePrice = distance * pricePerKmExecutive; const classicRidePrice = distance * pricePerKmClassic; // Format the ride prices and delivery price as currency strings const formattedExecutivePrice = executiveRidePrice.toLocaleString("en-US", { style: "currency", currency: "NGN" }); const formattedClassicPrice = classicRidePrice.toLocaleString("en-US", { style: "currency", currency: "NGN" }); const formattedDeliveryPrice = deliveryPrice.toLocaleString("en-US", { style: "currency", currency: "NGN" }); // 更新Executive Ride区块内容并显示 document.getElementById('executive-ride-price').textContent = formattedExecutivePrice; document.getElementById('executive-distance').textContent = `${distance.toFixed(2)}`; document.getElementById('executive-duration').textContent = duration; document.getElementById('executive-ride').classList.remove('hidden'); // 更新Classic Ride区块内容并显示 document.getElementById('classic-ride-price').textContent = formattedClassicPrice; document.getElementById('classic-distance').textContent = `${distance.toFixed(2)}`; document.getElementById('classic-duration').textContent = duration; document.getElementById('classic-ride').classList.remove('hidden'); // 更新Delivery Service区块内容并显示 document.getElementById('delivery-ride-price').textContent = formattedDeliveryPrice; document.getElementById('delivery-distance').textContent = `${distance.toFixed(2)}`; document.getElementById('delivery-duration').textContent = duration; document.getElementById('service-delivery').classList.remove('hidden'); } }); });
内容的提问来源于stack exchange,提问作者Emuekpere B. Erham
相关产品推荐
相关产品推荐

