查找文本(A)并将其替换为文本(B)+ HTML [英] Find text(A) and replace it with text(B) + HTML

查看:111
本文介绍了查找文本(A)并将其替换为文本(B)+ HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用jquery找到一些特定的文字,并用包含一些HTML的更新版本替换它。

I'd like to find with jquery some specific text, and replace it with a renewed version including some HTML.

我试过这个,当我只使用文字时工作:

I've tried this, which is working when I use only text:

<script type="text/javascript" >
    jQuery(document).ready(function(){

    jQuery("*").contents().each(function() {
    if(this.nodeType == 3)
    this.nodeValue = this.nodeValue.replace("hello mum", "bye bye mum");
    });

    })
</script>

但是,如果我添加一些文本+ HTML来替换目标表达式,它将被格式化并且被视为纯文本...

However, if I add some text + HTML to replace the targeted expression, it gets "formatted" and is read as plain text...

你知道这个问题的解决方案吗?
我可以在替换表达式中添加HTML吗?

Do you know guys some solution to this problem? Can I add HTML to the replacing expression?

谢谢。

推荐答案

jQuery在文本节点方面有点问题。此外,由于您直接操作文本节点的内容,因此所有HTML都将被视为文本。

jQuery is a little problematic when it comes to text nodes. Also, since you are directly manipulating the contents of a text node, all HTML will be considered as text.

我能想到的最简单的解决方案是有点hacky,但是效果很好:)

The simplest solution I can think of is a little hacky, but works great :)

用虚拟HTML元素替换文本节点。然后用替换HTML替换该虚拟HTML元素。

Replace the text node with a dummy HTML element. Then replace that dummy HTML element with your replacement HTML.

var isTextNode = this.nodeType == 3;
var matchesText = this.nodeValue.indexOf('hello mum') > -1;

if(isTextNode && matchesText) {
    // replace text node with dummy element
    // so jQuery can be used
    var dummy = $('<b>');
    this.parentNode.replaceChild(dummy[0], this);

    dummy.replaceWith('my <b>awesome</b> html now <i>works</i>');
}

这篇关于查找文本(A)并将其替换为文本(B)+ HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆