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

SweetAlert中focusConfirm不生效,默认聚焦Cancel而非OK按钮如何解决?

解决SweetAlert默认聚焦Cancel而非OK按钮的问题

看起来你遇到的问题是SweetAlert模态框的焦点没有按照预期落在OK按钮上对吧?我帮你排查了代码,问题出在按钮的键名定义上。

你代码里的取消按钮用了Cancel(首字母大写),但SweetAlert的标准按钮键名是小写的cancel。当你使用大写的键名时,SweetAlert会把它识别为一个自定义按钮,而非默认的取消按钮,这就导致focusConfirm: true的配置无法正确生效,焦点反而落到了Cancel按钮上。

解决方案

只需要把取消按钮的键名改成小写的cancel即可,修改后的完整代码如下:

function saveCase() { 
  if (recordedFullSymptoms.length != 0 && cust_preferenceFile.patient.patientId == 0) { 
    swal({ 
      text: "You can save the case by selecting or creating new patient.", 
      buttons: { 
        confirm: { 
          text: "Ok", 
          value: 1 
        }, 
        cancel: { // 修正为小写的cancel
          text:"Cancel", 
          value: 2 
        } 
      }, 
      focusConfirm: true, 
    }).then(value=> { 
      if(value==1){ 
        getPartialView('PatientList', this); 
      } 
    }) 
  } else { 
    swal("Please select atleast one symptom to save case."); 
  } 
}

额外验证方案

如果修改键名后仍有问题,你可以尝试直接给确认按钮添加autoFocus: true配置,强制让它获得焦点:

confirm: {
  text: "Ok",
  value: 1,
  autoFocus: true
}

不过优先推荐修改键名的方法,这更符合SweetAlert的标准API用法,能避免其他潜在的兼容问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:48:35