Sweetalert 2 textarea async

六眼飞鱼酱① 提交于 2020-01-04 01:36:09

问题


I tried with this simple example of documentation https://sweetalert2.github.io/ but i get the error message :

Uncaught SyntaxError: await is only valid in async function

$(document).ready(function() {
  $('.buttonproblem').click(function() {
    const { value : text } = await swal({
      input: 'textarea',
      inputPlaceholder: 'Type your message here',
      showCancelButton: true
    })

    if (text) {
      swal(text)
    }
  })   
});

回答1:


The issue is because you need to declare the click handler function as async in order to use the await keyword within it. Try this:

$('.buttonproblem').click(async function() { // note use of 'async' here
  const text = await swal({
    title: 'foo', // Note this was missing in your example
    input: 'textarea',
    inputPlaceholder: 'Type your message here',
    showCancelButton: true
  })

  if (text) {
    swal(text)
  }
})
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.js"></script>

<button class="buttonproblem">Click me</button>

Note that your const { value: text } syntax was causing an error, although the logic worked fine, so I removed it.



来源:https://stackoverflow.com/questions/49751053/sweetalert-2-textarea-async

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!