SweetAlert超链接如何设置Yes/No按钮动作,点击Yes跳转指定路由?
实现方法
你只需要在原有代码基础上补充两步即可实现需求:
- 点击按钮触发事件时先获取当前a标签的
href属性值存为变量 - 确认选择Yes的分支里,把存好的地址赋值给
window.location.href实现跳转
修改后的完整代码如下:
$(document).on('click', '#custombtn', function(e) { e.preventDefault(); // 获取当前点击的注册按钮对应的跳转地址 const redirectUrl = $(this).attr('href'); let form = $(this).parents('form'); swal( { title: "Alert!", text: "You have an active Wallet, do you wish to pay the price with the active Wallet?", type: "warning", allowEscapeKey: false, allowOutsideClick: false, showCancelButton: true, confirmButtonColor: "#DD6B55", confirmButtonText: "Yes", cancelButtonText: "No", showLoaderOnConfirm: true, closeOnConfirm: false }).then((isConfirm) => { if (isConfirm.value === true) { // 执行跳转逻辑 window.location.href = redirectUrl; } // 点击No不需要额外处理,默认停留在当前页面 }); });
原有{{ route('courseRegistration', $item->cor_id) }}已经在页面渲染时把实际的访问地址写入到a标签的href属性中,前端直接读取该属性跳转即可,不需要额外修改后端路由逻辑。如果需要新开标签页打开目标地址,可以把跳转逻辑替换为window.open(redirectUrl, '_blank')。
注意事项
如果你的页面存在多个课程注册按钮(比如课程列表场景),不要使用id选择器绑定事件,HTML中ID必须唯一,否则只有第一个按钮能触发弹窗,可以做如下适配:
- 把a标签的属性从
id="custombtn"修改为class="btn btn-info custombtn" - JS事件绑定代码修改为
$(document).on('click', '.custombtn', function(e) {
内容的提问来源于stack exchange,提问作者Pouya Vaghefi
相关产品推荐
相关产品推荐

