【问题标题】:How do I pass a value into a sweetalert?如何将值传递给 sweetalert?
【发布时间】:2020-11-29 16:33:44
【问题描述】:

我有一系列从数据库中填充的项目。我想在每个上都放一条甜蜜的更改状态确认消息。如何将他们的 ID 传递到 sweetalert 确认消息中?

在该部分中,我有一个功能,如果他们确认消息,我想运行它,如果他们不确认,我不希望它做任何事情。我在页面底部有以下代码,单击链接时会触发该代码。但是,我需要将 productID 传递到警报中,以便可以在 updateProducts 函数中调用它。

$(`.link`).click(function () {
    swal({
        title: "Are you sure?",
        text: "Are you sure you want to change the status?",
        icon: "warning",
        buttons: true,
        dangerMode: true,
    }).then((confirm) => {
        if (confirm) {
            updateProducts(productID);
        } else {
            swal("The status has not changed.");
        }
    });
})

【问题讨论】:

    标签: javascript jquery sweetalert sweetalert2


    【解决方案1】:

    看例子是你想要的吗?

    function updateProducts(y) {
      alert(y);
    }
    
    
    function someFunc(x) {
        swal({
              title: x , // <-- Passed Value
              text: "Are you sure you want to change the status?",
              icon: "warning",
              buttons: true,
              dangerMode: true,
            })
            .then((confirm) => {
              if (confirm) {
                updateProducts(x); // <-- do your code
              } else {
                swal("The status has not changed.");
              }
            });
    }
    
    
    let str = "My Value";
    
    
    
    
    
    $(`.link`).click(function () {
      someFunc(str); // <-- run this on click event.
    })
    .link { padding:30px; background: #40cc40; }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.2/sweetalert.min.js" integrity="sha512-AA1Bzp5Q0K1KanKKmvN/4d3IRKVlv9PYgwFPvm32nPO6QS8yH1HO7LbgB1pgiOxPtfeg5zEn2ba64MUcqJx6CA==" crossorigin="anonymous"></script>
    
    
    <button class="link">Click Me</button>

    【讨论】:

    • 太好了 - 谢谢!我试图在 Head 部分做类似的事情,但它必须在加载 DOM 之后。
    【解决方案2】:

    只需将您的 productID 存储在一个变量中,然后通过这样的函数传递它:

    $(`.link`).click(function () {
    
        var productID = 'productID';
        
        swal({
            title: "Are you sure?",
            text: "Are you sure you want to change the status?",
            icon: "warning",
            buttons: true,
            dangerMode: true,
        }).then((confirm) => {
            if (confirm) {
                updateProducts(productID);
            } else {
                swal("The status has not changed.");
            }
        });
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-14
      • 2021-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-19
      相关资源
      最近更新 更多