Home >Web Front-end >JS Tutorial >How to pop up prompt repeatedly in js

How to pop up prompt repeatedly in js

下次还敢
下次还敢Original
2024-05-01 06:27:161194browse

To repeatedly pop up the prompt() method of JavaScript, you need to use a loop or recursion: 1. Loop: use a while loop to continuously pop up the dialog box until the user cancels or enters an empty string; 2. Recursion: use a recursive function, automatically Calls itself until the user cancels or enters an empty string.

How to pop up prompt repeatedly in js

How to pop up prompt repeatedly in JavaScript

Use JavaScript's prompt() method. Repeatedly pops up a dialog box to collect user input. To do this, you need to use loops or recursion.

Method 1: Use a loop

<code class="javascript">while (true) {
  const input = prompt("请输入内容:");
  if (input === null || input === "") {
    break;
  }
  console.log(`用户输入:${input}`);
}</code>

This loop will continuously pop up the prompt() dialog box until the user clicks the cancel button or does not enter anything content.

Method 2: Use recursion

<code class="javascript">function promptRecursive() {
  const input = prompt("请输入内容:");
  if (input === null || input === "") {
    return;
  }
  console.log(`用户输入:${input}`);
  promptRecursive();
}

promptRecursive();</code>

This recursive function will automatically call itself until the user clicks the cancel button or enters nothing.

Note:

  • For method 1, you need to manually check whether the user clicked the cancel button or entered an empty string to end the loop.
  • For method 2, the recursion will run until the user clicks the cancel button or enters nothing. Therefore, in actual use, a condition needs to be used to determine when to end the recursion.

The above is the detailed content of How to pop up prompt repeatedly in js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:How to wrap prompt in jsNext article:How to wrap prompt in js