【问题标题】:How to pass parameters to the jquery alert function如何将参数传递给jquery alert 函数
【发布时间】:2017-07-28 15:32:39
【问题描述】:

我有一个带有删除按钮的 html 表。我想删除按钮单击时的行。为此,当我单击一个带有“.btn-danger”类的按钮时,它将打开一个 JQuery 警报窗口。我的问题是如何将按钮单击的 $(this) 传递给 $.alert Yes 函数,这样我就可以删除该行。我的代码如下。

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.1.0/jquery-confirm.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.1.0/jquery-confirm.min.js"></script>

$(document).ready(function() {
    $('.btn-danger').on('click', function(e){
        e.preventDefault();
        var me = $(this);
        var id = $(this).closest('tr').attr('id');
        $.alert({
            title: 'Alert!',
            content: 'Are you sure you want to delete data?',
            buttons: {
                Yes: function (me) {
                    //pass value
                },
                No: function () {
                    //close function
                }
            }
        });
    });
});

【问题讨论】:

  • 将 var me 设为全局

标签: javascript jquery


【解决方案1】:

你可以试试这样的代码(如果我正确理解你的问题)

$(document).ready(function() {
    $('.btn-danger').on('click', function(e){
        e.preventDefault();
        var me = $(this);
        $.alert({
            title: 'Alert!',
            content: 'Are you sure you want to delete data?',
            buttons: {
                Yes: function () {
                    me.closest('tr').remove();
                },
                No: function () {
                    //close function
                }
            }
        });
    });
});

jsfiddle example

【讨论】:

    【解决方案2】:

    Yes: function (me) {} 中删除me,因为您已经声明了它。然后你可以像下面这样调用它。

    Yes: function() {
        console.log(me)
    },
    

    $('.btn-danger').on('click', function(e) {
      e.preventDefault();
      var me = $(this);
      var id = $(this).closest('tr').attr('id');
      $.alert({
        title: 'Alert!',
        content: 'Are you sure you want to delete data?',
        buttons: {
          Yes: function() {
            console.log(me)
            //$("tr#" + id).remove() <--- example of removing the row
          },
          No: function() {
            //close function
          }
        }
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.1.0/jquery-confirm.min.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.1.0/jquery-confirm.min.css" rel="stylesheet" />
    
    <button class="btn btn-danger">delete</button>

    【讨论】:

    • 非常感谢
    猜你喜欢
    • 2013-01-27
    • 2010-09-27
    • 1970-01-01
    • 2012-02-13
    • 1970-01-01
    • 2011-04-16
    • 2017-02-05
    • 2014-10-18
    • 2011-01-23
    相关资源
    最近更新 更多