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

如何基于返回结果切换jQuery Sweet Alert的成功/错误图标?

解决Sweet Alert根据返回结果切换图标的问题

嘿,这问题很好搞定!核心思路就是根据返回的结果值做条件判断,动态指定Sweet Alert的图标类型就可以了。我给你两种实现方式,你可以根据自己的代码风格选:

方式一:简洁的三元运算符写法

如果你的代码比较追求简洁,用三元运算符一行就能搞定图标判断:

// 先拿到你的接口返回结果,这里用result变量代替,实际换成你自己的变量名
const result = "str4"; 

// 判断要显示的图标:如果是str2或str4就用error,否则用success
const alertIcon = (result === 'str2' || result === 'str4') ? 'error' : 'success';

// 调用Sweet Alert
Swal.fire({
  title: alertIcon === 'success' ? '操作完成' : '出现错误',
  text: result,
  icon: alertIcon,
  confirmButtonText: 'OK'
});

方式二:更直观的if-else写法

要是你觉得三元运算符有点绕,用if-else可读性更高,适合新手或者后续扩展复杂逻辑:

const result = "str2";
let alertIcon = 'success';
let alertTitle = '操作成功';

// 判断结果是否是指定的错误值
if (result === 'str2' || result === 'str4') {
  alertIcon = 'error';
  alertTitle = '操作失败';
}

// 弹出提示
Swal.fire(alertTitle, result, alertIcon);

额外提醒:处理异步场景

如果你的结果是从接口异步获取的(比如用fetch/axios),把判断逻辑放到请求成功的回调里就行,举个axios的例子:

axios.get('/your-api-url')
  .then(res => {
    const result = res.data; // 假设接口返回的字符串存在这里
    const alertIcon = (result === 'str2' || result === 'str4') ? 'error' : 'success';
    
    Swal.fire({
      title: alertIcon === 'success' ? '成功' : '错误',
      text: result,
      icon: alertIcon
    });
  })
  .catch(err => {
    // 请求失败时也可以弹错误提示
    Swal.fire('请求出错', err.message, 'error');
  });

小细节:注意字符串大小写

如果接口返回的字符串可能有大小写不一致的情况(比如STR2、Str4),可以统一转成小写再判断,避免漏判:

const alertIcon = (result.toLowerCase() === 'str2' || result.toLowerCase() === 'str4') ? 'error' : 'success';

这样不管返回的是大写还是小写,都能正确匹配啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 09:52:06