如何解决将html附加到包含“包含”的文本上
我想在找到文本时将html附加到文本上:
$( "div:contains(']')" ).append("<br>");
..这是错误的,因为我要针对此特定文本并添加html而不是在整个div上附加html。
解决方法
您需要迭代匹配元素所具有的文本节点,并在每个这些文本节点中的值中找到“]”。当文本节点具有此字符时,将文本节点一分为二,并在两者之间插入一个<br>
元素。
以下是您可以使用的一些代码:
$( "div:contains(']')" ).each(function () {
$(this).contents().each(function () {
if (this.nodeType !== 3) return; // Only interested in text nodes
let i; // position of the "]".
while ((i = this.nodeValue.indexOf("]")) >= 0) {
$(this).before(this.nodeValue.slice(0,i+1),$("<br>"));
this.nodeValue = this.nodeValue.slice(i+1);
}
});
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。