You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现下拉菜单随自动检测国家同步切换内容?

Alright, let's sort this out for you! The main pain points here are: your content block doesn't auto-switch when the dropdown is pre-selected via country detection, you need to replace the deprecated IP service, and you want to stop relying only on the onchange event. Here's a clean, updated solution that fixes all these issues:

Full Updated Code

HTML

<select id="countrySelect">
  <option value="GT">Guatemala</option>
  <option value="HN">Honduras</option>
  <option value="SV">El Salvador</option>
</select>
<div id="locations">
  <div id="GT" class="country">
    Content for Guatemala
  </div>
  <div id="HN" class="country">
    Content for Honduras
  </div>
  <div id="SV" class="country">
    Content for El Salvador
  </div>
</div>

CSS

.country {
  display: none;
}
.country:first-child {
  display: block;
}

JavaScript

// Utility function to hide all country content blocks
function hideAllContent() {
  Array.prototype.forEach.call(document.getElementById('locations').children, function(v){
    v.style.display = 'none';
  });
}

// Reusable function to sync both dropdown selection and content display
function showCountryContent(countryCode) {
  const contentEl = document.getElementById(countryCode);
  const selectEl = document.getElementById('countrySelect');
  
  if (contentEl) {
    hideAllContent();
    contentEl.style.display = 'block';
  }
  
  // Update dropdown to match the target country
  if (selectEl) {
    selectEl.value = countryCode;
  }
}

// Detect user's country using ipinfo.io
async function detectUserCountry() {
  try {
    const response = await fetch('https://ipinfo.io/json');
    const data = await response.json();
    const countryCode = data.country;
    
    // Only proceed if detected country is in our allowed list
    const validCountries = ['GT', 'HN', 'SV'];
    if (validCountries.includes(countryCode)) {
      showCountryContent(countryCode);
    } else {
      // Fallback to first option if country isn't supported
      showCountryContent(validCountries[0]);
    }
  } catch (error) {
    console.error('Failed to detect country:', error);
    // Fallback to default on detection failure
    showCountryContent('GT');
  }
}

// Set up dropdown change listener
document.getElementById('countrySelect').addEventListener('change', function() {
  showCountryContent(this.value);
});

// Run detection when the page finishes loading
window.addEventListener('load', detectUserCountry);

Key Fixes & Improvements

  • Reusable Logic: The showCountryContent function handles both updating the dropdown and switching content—so it works for both manual user selection and automatic detection. No more relying solely on onchange!
  • Updated IP Service: Switched from the deprecated freegeoip.net to ipinfo.io/json, using modern async/await for cleaner asynchronous code.
  • Error Resilience: Added fallback logic for failed detection or unsupported countries, so your page always shows valid content.
  • Cleaner Event Handling: Replaced inline onchange with a proper event listener—better practice for maintainable code.

内容的提问来源于stack exchange,提问作者Alejandro Hdz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 10:13:36