在不更改布局的情况下替换文本的解决方案(jQuery)

A solution to replace text without changing layout (jQuery)

本文关键字:文本 解决方案 jQuery 替换 情况下 布局      更新时间:2023-09-26

如何在不更改周围标记的情况下替换文本。$("content").text("some new text")将删除周围的标记。

<div id="content" style="height: 100%; width: 100%; padding: px;">
<p><strong>I need to be replaced</strong>
</p></div>
<div id="content" style="height: 100%; width: 100%; padding: 5px;">
<p><em><strong>I need to be replaced</strong></em></p>
</div>

如果你知道你总是替换强标记中的文本,你可以这样做。否则,你可能需要创建某种业务规则来确定你要替换内容块中的哪个元素。

$("#content strong").text("some new text")

如果除了可能有一个结构之外,你对封闭标签一无所知,你可以写这样的东西:

$.each($('.content'), function(i, val) {
  console.log($(val));
  replaceText(val, 'This is the updated text');
});
function replaceText(element, text) {
    if ($(element).children().size() == 0) {
       $(element).text(text);
       return;
    } 
    replaceText($(element).children()[0], text);
}

这将查找当前对象的子对象,如果有子对象,则在第一个子对象上向下移动DOM树。现在,如果一个元素有多个子元素,而您不知道要替换哪个子元素,则必须做更多的工作来创建业务规则。

如果您知道要替换的部分或全部文本,也可以在CSS中使用内容选择器:

$('.content').find(':contains("I also need to be replaced")').text('Update text');

链接到jsFiddle

感谢您的解决方案,非常有用!

re:如果你知道要替换的部分或全部文本,你也可以在CSS中使用内容选择器:

关键是:)$("#content").text()==我们想要替换的内容,

您的解决方案效果良好。我终于做了这个:

var content = $("#content").text();
$("#content").html($("#content").html().replace(content,"new text"));

谢谢!