与scanf()等效的Javascript

Javascript equivalent for scanf()

本文关键字:Javascript scanf      更新时间:2023-09-26

我想在一个使用的函数中向用户提出一系列问题

<input type="text" id="input">

在C中,scanf()函数允许您等待用户响应,并在用户输入值时继续。在JavaScript中,如果不使用prompt(),如何在函数中等待用户响应?

不幸的是,

prompt是最接近的等价物,但您已经要求了另一种选择——浏览器没有像c那样提供"等待"机制,因此没有直接的等价物。

浏览器中这个问题的标准解决方案(一系列问题)是一个表单,包含多个问题和答案以及它们自己的input字段。

您可以取消隐藏后续的input字段,作为验证前一个字段的效果。

具体来说,要想有一个回答多个问题的单一输入,您必须编写自己的解决方案。

有一种方法。我并没有在这里对用户输入进行消毒——如果它在生产中,你会想这样做的。

const input = document.getElementById('input');
const title = document.getElementById('title');
const resultsText = document.getElementById('resultsText');
const results = [];
let currentQuestion = "What is your name?";
const questions = [
  "What country do you live in?",
  "What is your primary language?"
]
const advanceForm = () => {
  results.push({
    q: currentQuestion,
    a: input.value
  })
  // Wipe input
  input.value = "";
  // Add next question
  title.innerHTML=questions[0];
  currentQuestion = questions[0];
  // If the questions array is not empty
  if (questions.length){
    // Save current input value to object
    questions.shift()
  } else {
    // If no question left, hide input and show info instead
    //Hide ID field
    input.style.visibility = "hidden";
    title.innerHTML = "Results:"
    // Represent the results as HTML
    const resultsAsHtml = results.map((result) => {
      return `<p>Question: ${result.q}</p><p>Answer: ${result.a}`
    })
    resultsText.innerHTML = resultsAsHtml
  }
}
input.addEventListener('keypress', (event) => {
    if (event.key === 'Enter') {
      advanceForm();
    }
});
<h3 id="title">What is your name?</h3>
<input type="text" id="input">
<p id="resultsText"><p>

您可以在js中使用onChange。

$(document).on('change','#input',function(e){
  e.preventDefault
});

您可以使用preventDefault()stopPropagation()

$(document).on('change','#input',function(event){
  event.preventDefault()
  event.stopPropagation()
});

有默认的javascript函数prompt();

参考

<!DOCTYPE html>
<html>
<body>
<p>Click the button to demonstrate the prompt box.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
    var person = prompt("Please enter your name", "Harry Potter");
    if (person != null) {
        alert( person );
    }
}
</script>
</body>
</html>