JavaScript prompt()替代方法 - 等待用户响应

3
我想在一个函数中向用户提出一系列问题。
如果我使用prompt(),就可以在一个函数中询问所有的问题。
function question(){
    var name = prompt("Enter your name");
    var age = prompt("Enter your age");
}

但是如果我尝试使用输入标签,这是不可能的。
function question(){
    document.write("Enter your name");

    // you can't wait until the user responds. It will simply execute all the lines at once. 

    name = document.getElementById("input").value;
    document.write("Enter your age");
    age = document.getElementById("input").value;
}

如果我这样做,我就不能在一个函数中使用输入标签向用户提问。我该如何等待用户的回答?
4个回答

2
为了连接提示,你可以这样做:

链式调用:

const name = prompt("Enter your name");
if (!!name) {
    const age = prompt("Enter your age");
    if(!!age){
      ...
    }
}

如果您的项目可以使用rxjs 5.5+,您可以使用Observable来等待第一个提示。 例如:

Original Answer翻译成"最初的回答"

of(prompt("Enter your name"))
.pipe(first(), filter((name) => !!name))
.subscribe((name) => {
    var age = prompt("Enter your age")
    if(age) {
        ...
    }
});

1
你可以将除第一个输入框外的所有输入框禁用。当用户对第一个输入框作出响应时,第二个输入框可以启用。输入行将继续按此方式进行。
这里有一个小演示,请注意这只是展示设计模式的示例代码。
<input id="name"></input> <button onClick="getInput()">Ok</button>

<input id="address"></input> <button onClick="getInput()" disabled>Ok</button>

并且在JS中

var name, address;

functon getInput() {

    name = document.getelementById("name").value;
    address = document.getElementById("address").value;

    if (address !== "")
        document.getElementById("address").removeAttribute("disabled");   

}

在JS中有许多比这更先进的方法可用。但是你可能应该先学习这个模式。


0

在一个函数中,你不能从同一个输入中获取两个不同的值。你应该创建另一个输入或一些按钮来区分变量。例如:

输入你的名字

输入你的年龄

保存

var bSave = window.document.getElementById('bSave');
bSave.addEventListener("click", question);

    var newName = window.document.getElementById('iName');
    var newAge = window.document.getElementById('iAge');

    function question() {
        name=newName.value;
        age=newAge.value;
    }
</script>

`


0

document.write() 用于编写 HTML,而不是像 prompt() 那样请求用户输入。你需要在用户提交表单之前进行输入验证,例如:

function checkQuestion(){
  if(document.getElementById("name").value == "")
    alert('name empty');
  if(document.getElementById("age").value == "");
    alert('age empty');
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接