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

关于在代码中使用模板实现按钮点击切换多语言文本的咨询

Great question! Let's walk through how to build this language toggle feature—we'll cover both vanilla JavaScript (no frameworks) and React, since you didn't specify which tech stack you're using. First, let's confirm your JSON files have a consistent structure (this is key for smooth swapping):

es.json

{
  "greeting": "Hola"
}

en.json

{
  "greeting": "Hello"
}
Vanilla JavaScript Implementation

Here's a straightforward approach using plain JS and the Fetch API to load your JSON files:

Step 1: Set up your HTML

First, create a button to trigger the toggle and an element to display the greeting:

<button id="langToggle">Switch Language</button>
<div id="greetingDisplay"></div>

Step 2: Add the JavaScript logic

We'll track the current language, fetch the corresponding JSON file, and update the display when the button is clicked:

// Initialize state: start with English
let currentLang = 'en';
const greetingDisplay = document.getElementById('greetingDisplay');
const langToggle = document.getElementById('langToggle');

// Function to load and display the greeting for the current language
async function loadGreeting() {
  try {
    const response = await fetch(`./${currentLang}.json`);
    const translations = await response.json();
    greetingDisplay.textContent = translations.greeting;
  } catch (error) {
    console.error('Failed to load translation file:', error);
    greetingDisplay.textContent = 'Oops!';
  }
}

// Load initial greeting
loadGreeting();

// Add click handler to toggle language
langToggle.addEventListener('click', () => {
  // Switch between 'en' and 'es'
  currentLang = currentLang === 'en' ? 'es' : 'en';
  // Update button text to reflect the next language (optional but user-friendly)
  langToggle.textContent = currentLang === 'en' ? 'Cambiar a Español' : 'Switch to English';
  // Reload the greeting
  loadGreeting();
});
React Implementation

If you're using React, we can leverage state hooks to manage the language and import the JSON files directly (Create React App supports importing JSON out of the box, no fetch needed):

Step 1: Import your JSON files

First, import the translation files at the top of your component:

import enTranslations from './en.json';
import esTranslations from './es.json';

Step 2: Build the component with state

Use useState to track the current language, and update the greeting when the button is clicked:

import { useState } from 'react';

function GreetingToggle() {
  // Initialize state with English
  const [currentLang, setCurrentLang] = useState('en');

  // Get the correct translation based on current language
  const greeting = currentLang === 'en' ? enTranslations.greeting : esTranslations.greeting;

  // Toggle language function
  const toggleLang = () => {
    setCurrentLang(prevLang => prevLang === 'en' ? 'es' : 'en');
  };

  return (
    <div>
      <button onClick={toggleLang}>
        {currentLang === 'en' ? 'Cambiar a Español' : 'Switch to English'}
      </button>
      <h1>{greeting}</h1>
    </div>
  );
}

export default GreetingToggle;

Quick Notes

  • Double-check your JSON file paths match where they're stored relative to your HTML/JSX files—adjust the fetch path or import statement if needed.
  • For larger apps with more translations, you might want to use a dedicated i18n library like i18next, but these methods work perfectly for this simple use case.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 07:57:35