在String / String位置后插入HTML

时间:2016-06-19 23:57:12

标签: javascript html regex

我已经找不到答案了,所以希望有人可以帮助我。

我尝试非破坏性地在文本中的子字符串或位置之前和之后插入HTML以创建新的内联元素或包装现有文本。我只是使用innerHTML并且已经完成了这个,但我真的想保留可能绑定到特定DOMNode的可能事件监听器。是否有一个Element的方法或原型将textNodes视为允许我在其之后或之前附加HTML的单个项目?

代码可能会像这样运行:

var testParagraph = document.getElementById("TestParagraph");

/** 
    text nodes would represent each item 
    that has been seperated by a space, for example 
**/

testParagraph.insertBefore(document.createElement("span"), testParagraph.textNodes[3])

谢谢你的时间!

2 个答案:

答案 0 :(得分:2)

如果要将dom元素插入到文本中,则不会出现事件处理程序问题,因为事件处理程序无法绑定到文本本身。在不破坏任何事件处理程序的情况下,更改DOM元素的内容是可能的,并且比您想象的更容易。

function insertAtStringPos(el, pos, insertable) {
    if(!el.children.length) {
        var text      = el.outerText;
        var beginning = document.createTextNode(text.substr(0, pos));
        var end       = document.createTextNode(text.substr(pos - text.length));

        while (el.hasChildNodes()) {
            el.removeChild(el.firstChild);
        }

        el.appendChild(beginning);
        el.appendChild(insertable);
        el.appendChild(end);
    }
}

示例:http://jsfiddle.net/9a8rxhp4/

答案 1 :(得分:1)

您可以使用split()来分割元素的文本。

var res = testParagraph.text().split(" ");
// each word is now in the res[0],res[1] ..
//and then you can create a textNode 
var textNode1 = document.createTextNode("before");
var textNode2 = document.createTextNode(res[0]); 

var spanElement = document.createElement("span");      
spanElement.appendChild(textNode1);
spanElement.appendChild(textNode2); 
//...   
//then return them into the testParagraph
testParagraph.appendChild(spanElement);
相关问题