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

JavaScript读取Quill编辑器HTML中mention元素的data-id属性

问题根因

原有代码无法获取到mention节点的data-id,通常由以下两个原因导致:

  • 全局调用document.querySelectorAll查询范围过大:如果Quill编辑器挂载在局部组件容器、Shadow DOM内部,全局查询无法命中编辑器内的节点
  • 若this.comment存储的是Quill输出的HTML字符串而非真实渲染的DOM节点,直接查询当前页面DOM自然无法匹配到对应元素
实现方案

根据你实际的业务场景选对应方案即可:

方案1:mention节点已渲染在页面的编辑器内

不要全局查询,将查询范围限定在Quill编辑器的根容器内即可:

sendComment(){
    console.log(this.comment);
    // 替换为你项目中Quill编辑器对应的容器选择器,默认类名为.ql-editor
    const editorRoot = document.querySelector('.ql-editor');
    const mentionNodes = editorRoot.querySelectorAll('span.mention');
    // 提取所有data-id存入数组
    const mentionIdList = Array.from(mentionNodes).map(node => node.dataset.id);
    console.log('提及用户ID列表:', mentionIdList);
}

注:标准HTML的data-*自定义属性可直接通过元素的dataset对象读取,无需调用getAttribute方法,写法更简洁。

方案2:仅持有Quill生成的HTML字符串,未渲染到页面

先将HTML字符串解析为临时DOM节点,再在临时节点内完成查询,无需把内容插入到页面中:

sendComment(){
    console.log(this.comment);
    // 创建临时DOM容器解析HTML字符串
    const tempDom = document.createElement('div');
    tempDom.innerHTML = this.comment;
    const mentionNodes = tempDom.querySelectorAll('span.mention');
    const mentionIdList = Array.from(mentionNodes).map(node => node.dataset.id);
    console.log('提及用户ID列表:', mentionIdList);
}

方案3:不依赖DOM的最稳妥方案(推荐)

直接读取Quill实例的Delta数据提取mention信息,完全不受DOM结构变动、渲染逻辑影响:

sendComment(){
    const mentionIdList = [];
    // quill替换为你项目中初始化完成的Quill实例对象
    const deltaContent = quill.getContents();
    deltaContent.ops.forEach(op => {
        if(op.insert?.mention){
            mentionIdList.push(op.insert.mention.id);
        }
    });
    console.log('提及用户ID列表:', mentionIdList);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 18:31:13