与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>
相关文章:
- 为什么不't Javascript对我的输入值进行了一些重新检查
- 创建一个类似链接的按钮,并通过Javascript函数打开一个新的弹出窗口
- 将函数的上下文应用于javascript变量
- 使用php或javascript从facebook相册URL中删除多余的部分
- 正在添加'X'按钮,在文本字段旁边使用javascript
- 如何在JavaScript中将字符串转换为函数引用
- 模糊事件的Javascript测试
- Javascript更改图标
- 如何将HTML id分配给元素,以及如何将JavaScript应用于元素
- 如何使用WCF服务和javascript表单post上传.doc文件
- javascript结合了数组和字典
- 这是什么 ==- javascript 运算符
- 从javascript创建一个列表
- 无法在通过jQuery的ajax加载的页面中执行javascript
- Javascript:selenium Web驱动程序isDisplayed()不工作
- 如何通过ajax刷新JSF填充的javascript变量
- 如何在Javascript中将JSon对象转换为数组
- Javascript生成的表单未提交
- 使用javascript将动态表从一个html页面打印到另一个html页
- 与scanf()等效的Javascript