简体   繁体   English

用新的HTML内容替换单词的每次出现

[英]Replace every occurrence of a word with a new HTML content

I'm trying to replace every occurrence of a word with a new HTML content. 我正在尝试用新的HTML内容替换单词的每次出现。 I have tried this: 我已经试过了:

function walk(node) {      
    var child, next;
    switch ( node.nodeType )  {
        case 1:  // Element
        case 9:  // Document
        case 11: // Document fragment
            child = node.firstChild;
            while ( child ) {
                next = child.nextSibling;
                walk(child);
                child = next;
            }
            break;
        case 3: // Text node
            handleText(node);
            break;
    }
}

function handleText(textNode) {
    var v = textNode.nodeValue;
    var replacement = "<h1>foo</h1>";
    v = v.replace(/toReplace/g, replacement);        
    textNode.nodeValue = v;
}

walk(document.body);

What I want is to replace all toReplace text with new actual HTML content (a foo in h1) but it just literally prints put <h1>foo</h1> 我想要的是用新的实际HTML内容(h1中的foo )替换所有toReplace文本,但实际上只是打印put <h1>foo</h1>

Fiddle: http://jsfiddle.net/7zkY8/ 小提琴: http : //jsfiddle.net/7zkY8/

How can I fix it? 我该如何解决?

Just simply replace the document.body.innerHTML , the browser will parse the text and reconstruct the DOM 只需替换document.body.innerHTML ,浏览器将解析文本并重建DOM

var replacement = "<h1>foo</h1>";
document.body.innerHTML = document.body.innerHTML.replace(/toReplace/g,replacement);

DEMO DEMO

This is how I did it 这就是我做的

function handleText(textNode) {
    if (textNode.nodeValue.match(/toReplace/)) {
        var parent = textNode.parentNode;
        var replacement = "<h1>foo</h1>";  
        textNode.nodeValue = textNode.nodeValue.replace(/toReplace/g, replacement);
        var newSpan = document.createElement('span');
        newSpan.innerHTML = textNode.nodeValue;
        parent.replaceChild(newSpan, textNode);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM