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

Bootstrap 5加载按钮失效求助:MetaMask连接按钮加载状态不生效

Bootstrap 5 MetaMask连接按钮加载状态修复方案

问题根源

  1. 箭头函数导致this指向错误:你使用箭头函数作为点击事件处理器,箭头函数的this不会绑定到触发事件的按钮元素,导致var $this = $(this);获取的不是目标按钮,后续的button('loading')自然无效。
  2. Bootstrap 5移除了jQuery按钮插件:Bootstrap 5不再支持button('loading')和button('reset')这类jQuery扩展方法,原写法在Bootstrap 5环境下无法生效。

具体修复步骤

1. 修正事件处理器的this指向

将箭头函数改为普通函数,确保$(this)正确指向点击的按钮:

$("#connectMetamaskBtn").on("click", async function() {
  const $btn = $(this);
  // 后续逻辑...
});

2. 手动实现加载状态逻辑

Bootstrap 5需要手动处理按钮的加载状态,核心步骤为:保存原始内容、替换加载提示、禁用按钮,操作完成后恢复状态。修改后的完整JS代码:

$("#connectMetamaskBtn").on("click", async function() {
  const $btn = $(this);
  const originalContent = $btn.html();

  // 设置加载状态
  $btn.html('<i class="fa fa-circle-o-notch fa-spin"></i> Connecting...').prop('disabled', true);

  try {
    provider = new ethers.providers.Web3Provider(window.ethereum);
    await provider.send("eth_requestAccounts", []);
    await startApp(provider);
    
    // 连接成功后的自定义逻辑,比如修改按钮状态为已连接
    $btn.html('Connected <img class="metamask-icon" src="assets/images/icons8-metamask-logo-48.png" width="25px" />').prop('disabled', true);
  } catch (e) {
    // 失败后重置按钮状态
    $btn.html(originalContent).prop('disabled', false);
    $("#error")
      .text(`An error occurred: ${e.message || e}`)
      .show();
  }
});

3. 可选:使用Bootstrap 5原生Spinner替代Font Awesome

如果想贴合Bootstrap风格,可替换为官方Spinner组件:

$btn.html('<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span> Connecting...').prop('disabled', true);

4. 检查依赖引入

  • 确保已正确引入Font Awesome(若使用原图标)
  • 确保jQuery已正确引入(代码中使用了$语法)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 15:05:21