You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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必须唯一,否则只有第一个按钮能触发弹窗,可以做如下适配:

  1. 把a标签的属性从id="custombtn"修改为class="btn btn-info custombtn"
  2. JS事件绑定代码修改为$(document).on('click', '.custombtn', function(e) {

内容的提问来源于stack exchange,提问作者Pouya Vaghefi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 00:54:03