使用SweetAlert创建故事

问题描述 投票:-1回答:1

我是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复制这个故事,但是我对如何在第二个提示下继续操作感到困惑(“你在饭桌上。你想吃点什么吗?”)。

任何人都可以在这里帮助我吗?

javascript sweetalert
1个回答
-1
投票

会使事情变得困难的是,尽管alertprompt暂停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();

[swalAlertswalPrompt是您要编写的新函数,它们接受标题和文本,调用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);
        });
    });
}
© www.soinside.com 2019 - 2024. All rights reserved.