如何使用模态对话框库将用户输入存储为变量? (JavaScript)

How to store user input as a variable with a modal dialog library? (JavaScript)

我正在尝试通过警报将用户输入保存为变量。我实际上可以使用 prompt 通过 JS 来完成,但无法使用 sweetalertsweetalert2[=35 实现类似的解决方案=] 图书馆。

我通读了他们的文档和示例:

https://sweetalert.js.org/guides/#advanced-examples
https://sweetalert2.github.io/#input-types

我的努力 return [Object promise] 在最好的情况下占位符而不是变量文本,但通常它根本不起作用: https://codepen.io/dimos082/pen/xeXmqK

以下是在 JavaScript 中适用于我的带有警报弹出窗口的实现: https://codepen.io/dimos082/pen/ROLEpo

<html>
<body>
    <button onclick="TellTale()">Tell me a story</button>
    <p id="Tale"></p>  <!-- Result from TellTale() will be put here as innerHTML-->  
</body>
<script> 
    function TellTale() {let KnightName = prompt("How do people call you, oh Noble Knight?");
    document.getElementById("Tale").innerHTML = "Once upon a time, there lived a champion, noble Sir " + KnightName + "."}
</script>
</html>

我寻找与上面代码中相同的变量处理。 这两个库是否可行,或者您可以建议一个更好的解决方案来替换标准警报?

谢谢!

您错误地处理了 Promise。请研究 Promises in ES5 以供参考。您为变量分配了一个 Promise 对象,它是异步的。它转到下一行附加了对象本身而不是 Promise 的值,因为该值未被解析 then.You 需要在使用 .then() 方法解析 Promise 时使用该值承诺。这是与 Promise 一起使用的修改后的 TellTale 方法:

function TellTale() {
     let KnightName = swal("How do people call you, oh Noble Knight?", 
     {
        content: "input",
     }).then(function(value){
           document.getElementById("Tale").innerHTML = "Once upon a 
           time, there lived a champion, noble Sir " + value + ".";
     });
}

我的解释可能看起来有点复杂,但是当您稍微研究一下 Promises 以及如何处理 resolve/reject 上的内容时就会明白了。

这个问题的解决方案:

<head>
    <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
    </head>
<html>
<body>
    <button onclick="TellTale()">Tell me a story</button>
    <p id="Tale"></p>  <!-- Result from TellTale() will be put here as innerHTML-->  
</body>
<script> 
function TellTale() {
 swal("How do people call you, oh Noble Knight?", {
   content: "input"
 }).then(KnightName => document.getElementById("Tale").innerHTML = "Once upon a time, there lived a champion, noble Sir " + KnightName + ".")
}
</script>
</html>