JavaScript 的資料輸入與資料取得

← 返回首頁

1) 可互動範例

為了教學,示範 alert 與頁面輸出兩種方式;正式網站請勿把密碼用 alert 顯示。

2) 原始程式碼(你提供的版本)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    帳號<input type="text" id="john"><br>
    密碼<input type="password" id="pw"><br>
     <input type="button"  onclick="say('wane')"  value="送出">
</body>
<script>
    //alert("hi say hello");
    function say(a)
    {
        s=document.getElementById("john").value;
        p=document.getElementById("pw").value;
        alert(a+"帳號:"+s+"密碼:"+p);
    }
  </script>
</html>

3) 改寫建議(較佳實務)

// 1) 避免建立隱性全域變數,請使用 const/let
function say(a) {
  const s = document.getElementById('john').value;
  const p = document.getElementById('pw').value;
  alert(a + ' 帳號:' + s + ' 密碼:' + p);
}

// 2) 或使用非 alert 的輸出方式
function show(){
  const s = document.getElementById('john').value;
  const p = document.getElementById('pw').value;
  document.getElementById('out').textContent = '帳號:' + s + '\n密碼:' + p;
}
提醒:正式上線時,密碼不應直接顯示或紀錄在前端畫面/alert,這裡只做教學示範。