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

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

我试图通过警报将用户输入保存为变量。我实际上可以通过JS使用提示来实现,但无法使用sweetalert和sweetalert2库实现类似的解决方案。

我仔细阅读了他们的文档和示例:

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

在最好的情况下,我的努力返回[对象承诺]占位符而不是变量文本,但通常,它根本不起作用: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>

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

谢谢!

javascript modal-dialog alert sweetalert sweetalert2
2个回答
1
投票

解决这个问题:

<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>

0
投票

你错误地处理了Promise。请研究Promises in ES5以获取参考。您为变量分配了一个Promise对象,该对象是异步的。它转到下一行附加了对象本身而不是Promise的值,因为该值未解析。当使用Promise上的.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以及如何处理解决/拒绝的东西时,我会解释清楚。

© www.soinside.com 2019 - 2024. All rights reserved.