添加和调整文本和符号

adding and adjusting text and symbols

本文关键字:符号 文本 调整 添加      更新时间:2023-09-26

我使用以下代码向#mydiv添加文本:

$('#mydiv').contents().filter(function() { 
    return this.nodeType == 3 
}).each(function(){ 
    this.textContent = this.textContent.replace('', 'line 1 line 2'); 
});

但是,我希望文本line 2使用换行符位于下一行。我在文本line 1line 2之间添加了'n,但这不起作用。

此外,我想在文本中使用一些符号(见此处),但如果我将其添加到文本中,则无法识别:

$('#mydiv').contents().filter(function() { 
    return this.nodeType == 3 
}).each(function(){ 
    this.textContent = this.textContent.replace('', '&#9986 line 1 &#9986 line 2'); 
});

JSFiddle示例

简单来说,CSS &#9986确实有效。

问题是因为您正在设置节点的textContent。这意味着对任何HTML或字符实体进行编码。相反,您需要设置父节点的innerHTML

$('#mydiv').contents().filter(function () {
    return this.nodeType == 3
}).each(function () {
    this.parentNode.innerHTML = this.textContent.replace('', '&#9986 line 1 <br /> &#9986 line 2');
});

小提琴示例