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

如何将指定div的aria-label文本提取并设置到modal-title元素中

解决方案

你的代码问题出在:$(".modal-form-details").attr('aria-label') 返回的是字符串,不是DOM元素,所以不能调用.clone()和.insertAfter()方法——这俩是操作DOM节点的,不是字符串的方法。

正确的实现步骤分3步:

  • 读取目标元素的aria-label属性值
  • 从字符串里提取出EARPLUG-xxxx部分
  • 将提取的内容设置到.modal-title的h4元素中

方法一:按空格分割取第一段(适合固定格式场景)

如果aria-label的格式固定是"[目标内容] dialog",直接按空格分割取第一个元素就行:

// 读取aria-label属性值
const ariaLabel = $(".modal-form-details").attr('aria-label');
// 提取目标文本片段
const targetText = ariaLabel.split(' ')[0];
// 将内容设置到h4元素
$(".modal-title").text(targetText);

方法二:用正则匹配(适配格式小变动)

如果aria-label的后缀不一定是dialog,但目标内容都是EARPLUG-开头加数字的格式,用正则匹配更健壮:

const ariaLabel = $(".modal-form-details").attr('aria-label');
// 匹配EARPLUG-开头、后续跟数字的内容
const matchResult = ariaLabel.match(/EARPLUG-\d+/);
if (matchResult) {
  $(".modal-title").text(matchResult[0]);
}

额外建议:增加元素存在性判断

避免因页面元素未加载/不存在导致报错,可以加个简单的校验:

const modalDetails = $(".modal-form-details");
const modalTitle = $(".modal-title");
// 确认两个元素都存在再执行逻辑
if (modalDetails.length && modalTitle.length) {
  const ariaLabel = modalDetails.attr('aria-label');
  const targetText = ariaLabel.split(' ')[0];
  modalTitle.text(targetText);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 09:11:31