在以编程方式插入 HTML 时,无法在 trix-editor 中为任何标签添加 ID 或类等属性

Posted

技术标签:

【中文标题】在以编程方式插入 HTML 时,无法在 trix-editor 中为任何标签添加 ID 或类等属性【英文标题】:Not able to add attribute like Id or class for any tag in trix-editor while inserting HTML programmatically 【发布时间】:2018-12-12 13:59:21 【问题描述】:

我试图在通过 java-script 插入 html 时在 trix-editor 中添加属性,如 id、span 标签的类,但是当我检查该标签的 DOM 时,编辑器从标签中删除了添加的属性。

我的 Java 脚本代码插入带有属性的 html:

element.editor.insertHTML("<span id='" + userId + "' class='mention-user'>" + userName + "</span >"); 

DOM:

 <div><!--block-->@<span style="font-size: 12px;">abc/span></div></trix-editor>

我也试过了:

element.editor.activateAttribute("href", "https://trix-editor.org/");

这工作正常,但无法添加 id 或类。有人可以在标签中添加 id 或 class 吗?

【问题讨论】:

【参考方案1】:

您可以通过多种方式使用它

纯js:

document.getElementsByTagName("span")[0].setAttribute("class", "mention-user");

document.getElementsByTagName("span")[0].setAttribute("id", userId);

或jquery:

$("span").attr("id",userId);
$("span").attr("class","mention-user");

不知道为什么,但是您使用 insertHtml 不知道您是否可以使用它添加 id 或 class 希望能回答你的问题

【讨论】:

以上是关于在以编程方式插入 HTML 时,无法在 trix-editor 中为任何标签添加 ID 或类等属性的主要内容,如果未能解决你的问题,请参考以下文章