【问题标题】:Angular2 - Sweetalert custom button click doesn´t workAngular2 - Sweetalert 自定义按钮单击不起作用
【发布时间】:2020-07-03 06:54:48
【问题描述】:

我像这样在 Sweetalert2 的页脚中创建了一个自定义按钮。

    Swal.fire({
          icon: "question",
          showCancelButton: true,
          confirmButtonColor: "#1976d2",
          cancelButtonText: "No",
          confirmButtonText: "Sí",
          footer: "<button (click)='withoutread()' class='btn btn-info'>Test</button>"
  })

  withoutread() {
    console.log('hello');
  }

问题:withoutread 函数没有正确调用,console.log('hello') 没有在控制台中显示 hello

那么:这段代码有什么问题?

【问题讨论】:

  • afaik (click) 是 Angular 语法,并且 Angular 不会重新编译代码,因此它不起作用。不确定普通的 js onclick 函数是否可以工作。
  • 尝试将按钮放在锚标签&lt;a&gt;&lt;button (click)='withoutread()' class='btn btn-info'&gt;Test&lt;/button&gt;&lt;/a&gt;

标签: angular sweetalert2


【解决方案1】:

工作!

Swal.fire({
  icon: 'error',
  title: 'Oops...',
  text: 'Something went wrong!',
  footer: '<button id="buttonId">Test</button>'
})

document.getElementById('buttonId').onclick = function(){
    alert('do Something');
}

【讨论】:

    【解决方案2】:

    由于方法 withoutread() 存在于 SweetAlert 实例的范围之外,因此无法访问您实现该方法的 click 方法。

    除了用于捕获用户输入的 SweetAlert configurations available,您还可以包含第三个自定义按钮并使用事件委托捕获点击,如 here 所述

    【讨论】:

    • 我想向 sweetalert2 modal 添加第三个按钮,所以这不是我需要的。
    • 可以使用事件委托。我会更新答案。
    【解决方案3】:

    试试这个

    footer: "<a><button (click)='withoutread()' class='btn btn-info'>Test</button></a>"
    

    footer: "<a onclick='withoutread()'><button class='btn btn-info'>Test</button></a>"
    

    【讨论】:

      【解决方案4】:

      您必须使用 onclick 而不是 (click)。请看下面的工作代码。

      Swal.fire({
            icon: "question",
            showCancelButton: true,
            confirmButtonColor: "#1976d2",
            cancelButtonText: "No",
            confirmButtonText: "Sí",
            footer: "<button onclick='withoutread()' class='btn btn-info'>Test</button>"
      })
       function withoutread() {
           alert('dd') 
       }
      

      您还可以查看 JSFiddle 链接 here

      【讨论】:

        猜你喜欢
        • 2017-07-09
        • 2014-02-10
        • 1970-01-01
        • 2023-04-05
        • 1970-01-01
        • 2012-05-29
        相关资源
        最近更新 更多