开发者

Inserting br into a textnode

开发者 https://www.devze.com 2023-02-26 01:10 出处:网络
This might seem odd. I have a div with the id of \'quotes\', and inside there is a blockquote. I thought it would be interesting to add line breaks, if the quoted text were poetry, and I thought you c

This might seem odd. I have a div with the id of 'quotes', and inside there is a blockquote. I thought it would be interesting to add line breaks, if the quoted text were poetry, and I thought you could use a '@' as a conditional line break, and then replace this with the br element as follows:

function addBr() {
    var c = document.getElementById("quotes");
    var t = c.getElementsByTagName("blockquote");    
    var reg = new RegExp("@", "g");
    for (var i = 0; i < t.length; i++) {
        var r = t[i].lastChild.nodeValue.match(reg);
        if (r !== null) {
            var text = t[i].childNodes[0];
            var q = t[i].lastChild.nodeValue.indexOf("@");
            var x = document.createElement("br");
            t[i].insertBefore(x, text.splitText(q));
            t[i].lastChild.nodeValue = t[i].lastChild.nodeValue.replace(/\@/g, "");
        }
    }
}

This works, but only for the first instance, so I need a loop, but I can't f开发者_JS百科igure that out. The div would be like this:

<div id = 'quotes'>
<blockquote> Some line, @ Some line, @ Some line@ </blockquote>
</div>

Any hints would be deeply appreciated.


Start with the last match of @ within the text node and work backwards. The following function does this and also has the benefit of eliminating the unnecessary regex, uses clearer variable names and is shorter:

function addBr() {
    var c = document.getElementById("quotes");
    var t = c.getElementsByTagName("blockquote");
    for (var i = 0; i < t.length; i++) {
        var splitPos, textNode = t[i].lastChild;

        while ( (splitPos = textNode.data.lastIndexOf("@")) != -1 ) {
            var newTextNode = textNode.splitText(splitPos);

            // Remove the @ from the start of the new text node
            newTextNode.deleteData(0, 1);

            var br = document.createElement("br");
            t[i].insertBefore(br, newTextNode);
        }
    }
}


I would suggest simply doing this:

function addBr() {
    var c = document.getElementById("quotes");
    var t = c.getElementsByTagName("blockquote");    
    for (var i = 0; i < t.length; i++)
        r.innerHTML = r.innerHTML.replace(/@/g, "<br />");
}

What is a "conditional line break"? I don't see anything in your code that decides when to break the line...

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号