如何使用JavaScript根据页面语言生成不同的Facebook链接?
Dynamic Facebook Link Href Based on Page Language
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
DOMContentLoadedor place it right before the closing</body>tag. This ensures the#fbelement exists before you try to modify it. - Case Consistency: Converting the language value to lowercase prevents issues if the
langattribute uses uppercase (likeLang="AR"). - Fallback URL: Adding a default case ensures the link still works if the language isn't Arabic or English.
内容的提问来源于stack exchange,提问作者Mohamed Abubakkar
相关产品推荐
相关产品推荐

