溫馨提示×

如何用JS Prompt顯示錯誤信息

js
小樊
81
2024-10-12 21:42:22
欄目: 編程語言

在JavaScript中,prompt()函數(shù)用于顯示一個(gè)對話框,提示用戶輸入信息。然而,prompt()函數(shù)本身并不支持直接顯示錯誤信息。如果你想向用戶顯示錯誤信息,你可以使用alert()console.error()或其他方法。

下面是一個(gè)例子,展示了如何使用alert()在用戶點(diǎn)擊“確定”按鈕后顯示錯誤信息:

function showError(message) {
  alert('錯誤: ' + message);
}

let userInput = prompt('請輸入一些信息:');

if (userInput === null) {
  // 用戶點(diǎn)擊了取消按鈕
  console.log('用戶取消了輸入');
} else {
  let errorMessage = '輸入不能為空';
  if (!userInput.trim()) {
    errorMessage = '輸入不能為空';
  } else if (userInput.length < 5) {
    errorMessage = '輸入長度至少為5個(gè)字符';
  }
  
  if (errorMessage) {
    showError(errorMessage);
  } else {
    console.log('用戶輸入了有效信息:', userInput);
  }
}

在這個(gè)例子中,我們首先定義了一個(gè)showError()函數(shù),它使用alert()顯示錯誤信息。然后,我們使用prompt()提示用戶輸入信息。如果用戶點(diǎn)擊了取消按鈕(即返回null),我們會在控制臺中記錄一條消息。如果用戶輸入了信息,我們會檢查輸入是否有效,并在必要時(shí)調(diào)用showError()函數(shù)顯示錯誤信息。

0