jquery - 如何从同名按钮数组中的按钮单击中获取正确的值?
问题描述
我正在使用 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)。我错过了什么?谢谢
解决方案
的.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);
}
});
});
});
推荐阅读
- javascript - Postman:从 JSON Array 中获取数组值并将其设置为 postman 变量
- git - 壁球合并后的 Git 冲突
- node.js - 即使我添加了安全组,也无法在特定端口上访问 EC2
- javascript - 如何从选择选项中获取子跨度文本
- php - 为什么即使模型名称在 Laravel 上是复数,它也能工作?
- dart - 在 Dart 中使用 Sink 和 Pipe 与 Streams 有什么区别?
- javascript - JSON 对象返回未定义,即使它存在(NASA API 和 React)
- python - 参考以下代码,返回如何以递归方式工作
- mysql - 删除后跳跃ID自动递增
- command-line - casperjs命令行参数失败