DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> CSS入門知識 >> CSS詳解
輸入英文單字自動翻中文:用 switch 做一本小字典
編輯:CSS詳解     

想在一個網頁裡放一本迷你字典,最直白的做法就是 switch:把查詢到的單字轉小寫,逐一比對 case,命中就呼叫一個函式把中文寫進另一個欄位。這個範例收錄了幾十個日常單字,很適合當 JavaScript 條件判斷的入門練習。

HTML 與函式骨架

<script>
function asd(word) {
  document.f1.sWord.value = word;
}

function translate() {
  var e = document.f1.eWord.value;
  e = new String(e);
  e = e.toLowerCase();

  switch (e) {
    case "who":     asd("誰");     break;
    case 'what':    asd('什麼');   break;
    case 'dog':     asd('狗');     break;
    case 'hello':   asd('你好');   break;
    case 'bye':     asd('再見');   break;
    case 'head':    asd('頭');     break;
    case 'face':    asd('臉');     break;
    case 'nose':    asd('鼻子');   break;
    case 'eye':     asd('眼睛');   break;
    case 'computer':asd('電腦');   break;
    case 'notebook':asd('筆記本'); break;
    case 'sorry':   asd('對不起'); break;
    // 其餘單字照這個格式往下補
  }
}
</script>

<form name="f1">
  <input type="text" name="eWord" size="10" maxlength="50">
  --->
  <input type="text" name="sWord" size="10" maxlength="50">
  <input type="button" value="翻譯" onclick="translate()">
</form>

兩個容易忽略的細節

  • 一定要轉小寫:toLowerCase() 讓「Hello」「HELLO」「hello」都能查到同一筆,這是多數初學者會漏掉的一步。
  • 每個 case 都要 break:少了 break 就會一路往下執行(fall through),把後面所有單字的翻譯都跑一遍。
  • document.f1.sWord 是靠表單名稱加欄位名稱直接取值,寫得短但可讀性普通,正式專案建議改用 getElementById。

更現代的寫法

當字庫變大,switch 會長得難以維護。改用物件對照表會清爽很多,查詢也變成一行:

var dict = { dog: '狗', hello: '你好', sorry: '對不起' };
var word = document.getElementById('eWord').value.trim().toLowerCase();
document.getElementById('sWord').value = dict[word] || '查無此字';

這個版本還少了「查不到」的處理——原本的 switch 沒有 default,遇到字庫外的單字會靜默無事。加上 dict[word] || '查無此字' 之後,回饋就完整了。若要擴充成真正的翻譯工具,則需要接上 API,但作為語法練習,這段小程式把函式、表單取值與條件判斷都串起來了。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved