【问题标题】:Swal.fire when click text in Javascript (Sweetalert)单击 Javascript 中的文本时发生 Swal.fire (Sweetalert)
【发布时间】:2021-05-30 11:41:38
【问题描述】:

当我单击文本时,我想显示一个带有 sweetalert (swal.fire) 的窗口提示。 if 语句和窗口提示如何在这个库上工作?在此之后,您可以体会到我是这个编程世界的新手。

之后,我想为该输入分配一个值并验证答案是否正确。

<td class="gases" title="Hidrógeno" id="H">H</td>这是我要点击的元素

Swal.fire({
title:'¿Cuál es el elemento?',
text: 'Introduce el nombre aquí',
input: 'text',
inputPlaceholder: 'Nombre', })

这是我单击该元素时想要出现的提示。单击“确定”按钮时,要验证所介绍的名称是否正确...:

if (name === hidrógeno) {
     Swal.fire ('Correct!', 'You got the answer right!', 'success') }

else {
     Swal.fire ('Incorrect...', 'You failed!', 'error') }

【问题讨论】:

    标签: javascript html if-statement sweetalert2


    【解决方案1】:

    首先将单击事件侦听器附加到您希望可点击的文本。你可以通过使用querySelector() 和它的类名来获取你的元素,然后使用.addEventListener() 向它添加一个点击事件处理程序:

    const elem = document.querySelector(".gases");
      elem.addEventListener("click", () => {    
    });
    

    在 addEventListener 的回调函数中,您可以使用 Swal.fire() 打开您的甜蜜问题弹出窗口。此方法返回一个promise,它解析为用户输入的文本。要从这个 Promise 中获取解析值,您可以附加 .then()destructure 从参数中输入的文本:

    const elem = document.querySelector(".gases");
    elem.addEventListener("click", () => {
      Swal.fire({
        title: '¿Cuál es el elemento?',
        text: 'Introduce el nombre aquí',
        input: 'text',
        inputPlaceholder: 'Nombre',
      }).then(({value}) => {
        if (value === "hidrógeno") {
          Swal.fire('Correct!', 'You got the answer right!', 'success')
        } else {
          Swal.fire('Incorrect...', 'You failed!', 'error')
        }
      });
    });
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.16/dist/sweetalert2.all.min.js"></script>
    
    <table>
      <tr>
        <td class="gases" title="Hidrógeno" id="H">Click</td>
      </tr>
    </table>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-07
      • 2013-12-18
      • 2015-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多