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

如何使待办事项的编辑按钮(Swal.fire输入版)正常工作?

问题分析:Swal.fire 是异步操作,你用了同步逻辑处理

你遇到的核心问题是:Swal.fire() 是异步函数,它返回的是一个 Promise 对象,而不是用户直接输入的文本。之前用 prompt() 时是同步执行——代码会等用户输入完才继续,但 Swal.fire 不会阻塞代码,所以你直接拿 newText 去调用 filtroList 时,它其实是个 Promise,不是字符串,自然无法正常赋值。

解决方案:用异步方式处理 Swal 的返回值

下面提供两种简单的修改方式,任选其一即可解决问题:

方式1:使用 async/await(更易读)

把 editarText 声明为异步函数,用 await 等待用户完成输入:

//Funcion edit
const editarText = async (e) => {
  const nuevoText = document.getElementById(`text${e}`);
  // 等待用户操作完成,获取弹窗结果
  const result = await Swal.fire({
    title: 'Ingrese nuevo texto',
    input: 'text',
    inputPlaceholder: 'Nuevo Texto...'
  });

  // 检查用户是否点击确认,且输入有效
  if (result.isConfirmed && result.value) {
    const validatedText = filtroList(result.value);
    if (validatedText) {
      nuevoText.innerHTML = validatedText;
    }
  }
};

方式2:使用 .then() 链式调用

如果不习惯 async/await,也可以用 Promise 的 then 方法处理结果:

//Funcion edit
const editarText = (e) => {
  const nuevoText = document.getElementById(`text${e}`);
  Swal.fire({
    title: 'Ingrese nuevo texto',
    input: 'text',
    inputPlaceholder: 'Nuevo Texto...'
  }).then((result) => {
    // 确认用户点击了确认按钮且有输入
    if (result.isConfirmed && result.value) {
      const validatedText = filtroList(result.value);
      if (validatedText) {
        nuevoText.innerHTML = validatedText;
      }
    }
  });
};

额外优化建议

为了提升用户体验,你可以把输入验证直接集成到 Swal 弹窗里,避免重复弹出错误提示:

const result = await Swal.fire({
  title: 'Ingrese nuevo texto',
  input: 'text',
  inputPlaceholder: 'Nuevo Texto...',
  // 直接在弹窗里验证输入长度
  inputValidator: (value) => {
    if (!value || value.length < 3) {
      return 'Ingrese 3 o más caracteres!';
    }
  }
});

这样用户输入不符合要求时,Swal 会直接在弹窗底部显示提示,不用再触发你原来的错误弹窗,逻辑更顺畅。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 17:44:05