【问题标题】:How to get the proper value from button click in array of buttons with the same name?如何从同名按钮数组中的按钮单击中获取正确的值?
【发布时间】:2018-10-14 03:08:43
【问题描述】:

我正在使用 laravel/ajax,我想为内容表中的每一行创建一个删除按钮。因此,在我的 foreach 中(在我看来),我正在创建具有相同名称和不同值的删除按钮。

 <button value="{{$group->id}}" name="destroy"><i class="zmdi zmdi-delete zmdi-hc-fw"></i></button>

现在我有一个 jquery ajax 调用:

 $('button[name="destroy"]').on('click', function(e) {

    swal({
        title: "Are you sure?",
        text: "Once you delete this row, you can not rollback it",
        type: "warning",
        showCancelButton: true,
        buttonsStyling: false,
        confirmButtonColor: '#dd394a',
        confirmButtonText: 'Yes, I am sure!',
        cancelButtonText: "No, cancel it!",
        background: 'rgba(0, 0, 0, 0.96)',
        confirmButtonClass: 'btn btn-sm btn-light',
    }).then(function() {

        $.ajax({

            url: 'Groupe/destroy/'+ $('button[name="destroy"]').trigger('change').val(),
            type: 'POST',

            success: function(data)
            {
                $('.modal-content').html(data);
            }
        });
    });
});

执行此操作后,每次单击按钮(当我在成功部分中使用 $('button[name="destroy"]').trigger('change').val() 编写警报时)都会首先返回相同的结果值,感觉就像它总是从行中的第一个按钮读取值并为所有其他按钮重复它。 (在检查元素中,每个按钮都有不同的 ID)。我错过了什么?谢谢你

【问题讨论】:

    标签: jquery ajax laravel-5 ajaxform


    【解决方案1】:

    .on( 'click', handler ) 的值在this.value 中对应于被点击的按钮。

    试试这个:

        $('button[name="destroy"]').on('click', function (e) {
    
            var btnValue = this.value;
    
            swal({
                title: "Are you sure?",
                text: "Once you delete this row, you can not rollback it",
                type: "warning",
                showCancelButton: true,
                buttonsStyling: false,
                confirmButtonColor: '#dd394a',
                confirmButtonText: 'Yes, I am sure!',
                cancelButtonText: "No, cancel it!",
                background: 'rgba(0, 0, 0, 0.96)',
                confirmButtonClass: 'btn btn-sm btn-light',
            }).then(function () {
    
                $.ajax({
    
                    url: 'Groupe/destroy/' + btnValue,
                    type: 'POST',
    
                    success: function (data) {
                        $('.modal-content').html(data);
                    }
                });
            });
        });
    

    【讨论】:

    • 我不知道我怎么错过了那部分。谢谢,它有效:)
    猜你喜欢
    • 2021-12-08
    • 1970-01-01
    • 2020-12-04
    • 1970-01-01
    • 2018-06-12
    • 2022-01-16
    • 2017-04-28
    • 2019-04-02
    相关资源
    最近更新 更多