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

如何使用JavaScript或jQuery从HTML文本串中提取dx-mention类span的data-mention-value

核心实现思路

不需要把HTML字符串插入到当前页面渲染,仅在内存中创建临时DOM节点解析字符串结构,即可提取目标属性值,不会影响现有页面状态。

方案1:原生JavaScript实现
// 待解析的HTML文本字符串
const htmlStr = `<p>
  <span class="dx-mention" spellcheck="false" data-marker="@" data-mention-value="AgnesGan" data-id="AgnesGan">
    <span contenteditable="false">
      <span>@</span>
      AgnesGan
    </span>
  </span> 
  <span class="dx-mention" spellcheck="false" data-marker="@" data-mention-value="AK" data-id="AK">
    <span contenteditable="false">
      <span>@</span>AK
    </span>
  </span>
</p>`;

// 创建内存中的临时DOM容器
const tempContainer = document.createElement('div');
// 传入HTML字符串,浏览器自动完成DOM解析
tempContainer.innerHTML = htmlStr;

// 选中所有class为dx-mention的span标签
const mentionNodes = tempContainer.querySelectorAll('span.dx-mention');
// 提取data-mention-value属性值
const mentionValues = Array.from(mentionNodes).map(node => node.dataset.mentionValue);

console.log(mentionValues); // 输出结果:['AgnesGan', 'AK']
方案2:jQuery实现
// 待解析的HTML文本字符串
const htmlStr = `<p>
  <span class="dx-mention" spellcheck="false" data-marker="@" data-mention-value="AgnesGan" data-id="AgnesGan">
    <span contenteditable="false">
      <span>@</span>
      AgnesGan
    </span>
  </span> 
  <span class="dx-mention" spellcheck="false" data-marker="@" data-mention-value="AK" data-id="AK">
    <span contenteditable="false">
      <span>@</span>AK
    </span>
  </span>
</p>`;

// 用jQuery直接解析HTML字符串为jQuery对象
const $html = $(htmlStr);
// 筛选目标元素并提取属性
const mentionValues = $html.find('span.dx-mention').map(function () {
  return $(this).data('mention-value');
}).get();

console.log(mentionValues); // 输出结果:['AgnesGan', 'AK']

补充说明:如果HTML字符串来源不可信,直接赋值innerHTML会有XSS注入风险,建议先做恶意内容过滤再执行解析操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 14:24:04