我是JavaScript的初学者,想知道如何有效地使用SweetAlert library创建故事。我已经使用Windows提示和警报来创建一个类似这样的故事:
javascript
alert("Hello, we are now going to talk about you now.");
var Name = prompt("What is your Name?");
while (Name === "" || Name == null ) {
alert("Please type a name in the field!")
var Name = prompt("Type in your name");
}
alert(Name + "? That is my friend's name as well! ");
var things = prompt("You are at the dinner table. Would you like to have something?");
while (things == "" || things == null ) {
alert("Choose something!")
var Name = prompt("Have something!");
}
这是我第一次使用SweetAlert:
javascript
swal({
title: "Hello, we are now going to talk about you now.",
text: "What is your name?",
type: "input",
showCancelButton: false,
closeOnConfirm: false,
inputPlaceholder: "Write something"
}, function (Name) {
if (Name === false) return false;
if (Name === "") {
swal.showInputError("Please type a name in the field!");
return false
}
swal("Nice!", "I can confirm that you wrote: " + Name, "success");
});
现在,我正在尝试在我的调查平台上使用SweetAlert复制这个故事,但是我对如何在第二个提示下继续操作感到困惑(“你在饭桌上。你想吃点什么吗?”)。
任何人都可以在这里帮助我吗?
会使事情变得困难的是,尽管alert
和prompt
暂停javascript的执行直到关闭,而sweetalerts不会暂停执行,所以您必须使用回调函数在关闭时进行响应。
这里工作的正确工具是异步并等待(承诺而不是回调),在这种情况下尤其如此,因为您将许多“然后是”链接在一起。
您可以做这样的事情:
async function tellStory() {
await swalAlert("Hello, we are now going to talk about you now.");
let name = await swalPrompt("What is your Name?");
while (!name) {
await swalAlert("Please type a name in the field!");
name = await swalPrompt("Type in your name");
}
}
tellStory();
[swalAlert
和swalPrompt
是您要编写的新函数,它们接受标题和文本,调用swal
,并返回在swal回调函数中解析的Promise。
例如swalPrompt
看起来像这样
function swalPrompt(title, text) {
return new Promise(resolve => {
swal({
title: title,
text: text,
type: "input",
showCancelButton: false,
closeOnConfirm: true,
inputPlaceholder: "Write something"
}, function(name) {
resolve(name);
});
});
}