gpt4 book ai didi

javascript - Jquery字符串替换无法在前后添加html元素

转载 作者:行者123 更新时间:2023-11-28 10:16:35 25 4
gpt4 key购买 nike

这是我的 jquery 脚本,它将字符串替换为新字符串:

$("*").contents().each(function() {
if(this.nodeType == 3)
this.nodeValue = this.nodeValue.replace("1.(800).123.1234", "new");
});

工作示例:http://jsfiddle.net/webdesignerart/eKRGT/

但我想在字符串 html 元素之前和之后添加 new

当我这样做时:

  this.nodeValue = this.nodeValue.replace("1.(800).123.1234", "<b>new</b>");

结果来了:

<b>new</b>

我想要输出:

我想在替换过程中允许使用 html 标签。

jquery .append 可以使用它。

最佳答案

您正在替换 TextNode 元素的内容,该元素始终只是文本。要使文本变为粗体,您需要创建另一个元素 b,它包围 TextNode。一种方法是使用 jQuery 中的 wrap():

$("*").contents().each(function() {
var me = this;
if(this.nodeType == 3)
this.nodeValue = this.nodeValue.replace("1.(800).123.1234", function(a){
$(me).wrap('<b />');
return "new";
});
});

示例:http://jsfiddle.net/niklasvh/eLkZp/

关于javascript - Jquery字符串替换无法在前后添加html元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6491805/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com