首页 > 解决方案 > 如何从同名按钮数组中的按钮单击中获取正确的值?

问题描述

我正在使用 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)。我错过了什么?谢谢

标签: jqueryajaxlaravel-5ajaxform

解决方案


.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);
                }
            });
        });
    });

推荐阅读