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

如何使用JavaScript根据页面语言生成不同的Facebook链接?

Hey there! Great question—here's a straightforward way to dynamically update that Facebook link's href based on your page's language using vanilla JavaScript:

Method 1: Detect Language from HTML lang Attribute

Most multilingual sites set the lang attribute on the root <html> tag (like <html lang="en"> or <html lang="ar">). We can use this to determine the page's language:

// Wait for the DOM to fully load before manipulating elements
document.addEventListener('DOMContentLoaded', function() {
  // Get the Facebook link element by its ID
  const fbLink = document.getElementById('fb');
  
  // Get the page's language from the <html> tag, convert to lowercase for consistency
  const pageLang = document.documentElement.lang.toLowerCase();
  
  // Set the appropriate href based on the detected language
  if (pageLang === 'ar') {
    fbLink.href = 'https://www.facebook.com/ar';
  } else if (pageLang === 'en') {
    fbLink.href = 'https://www.facebook.com/en';
  } else {
    // Optional: Set a default URL if the language isn't Arabic or English
    fbLink.href = 'https://www.facebook.com';
  }
});

Method 2: Use a Global Language Variable

If your project uses a global variable to track the current language (common in frameworks or multilingual libraries), you can skip detecting the lang attribute and use that directly:

document.addEventListener('DOMContentLoaded', function() {
  const fbLink = document.getElementById('fb');
  // Assume you have a global variable like window.currentLang
  const currentLang = (window.currentLang || 'en').toLowerCase();
  
  switch(currentLang) {
    case 'ar':
      fbLink.href = 'https://www.facebook.com/ar';
      break;
    case 'en':
      fbLink.href = 'https://www.facebook.com/en';
      break;
    default:
      fbLink.href = 'https://www.facebook.com';
  }
});

Key Notes

  • DOM Load Timing: Always wrap your code in DOMContentLoaded or place it right before the closing </body> tag. This ensures the #fb element exists before you try to modify it.
  • Case Consistency: Converting the language value to lowercase prevents issues if the lang attribute uses uppercase (like Lang="AR").
  • Fallback URL: Adding a default case ensures the link still works if the language isn't Arabic or English.

内容的提问来源于stack exchange,提问作者Mohamed Abubakkar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 15:22:30