本文介绍了Javascript:如何获取文本节点后面/前面的break标记并用ddb标记包装它们?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在Jquery中完成了这个,但是想要在Javascript中实现而不依赖于任何库。

I have accomplished this in Jquery but would like an implementation in Javascript without dependence on any libraries.

$("br",document).parent().contents().each(function() {
    var text = this.textContent ? this.textContent : this.innerText;
    text = this.textContent.replace(/\s+/g, '')
    if ( this.nodeType == 3 && text.length != 0) {
        $(this).wrap('<ddb></ddb>')
    }
});


推荐答案

以下代码应与您完全相同功能确实。

The following code should do the exact same thing as your function does.

<html>

<body>
Hello
<p>
Hello
<br/>
Hello 2
<br/>

     <br/>      
<br/>
</p>

<button onclick="wrapText()">Wrap</button>

<script type="text/javascript">
    function wrapText() {
        var nodeList = document.getElementsByTagName('br');
        for (var i=0; i < nodeList.length; i++) {
            var node = nodeList[i];
            var parentNode = node.parentNode;
            if (!parentNode) continue;
            for (var c=0; c < parentNode.childNodes.length; c++) {
                var child = parentNode.childNodes[c];
                if (child.nodeType != 3) continue;

                if (child.nodeValue.match(/[^\s]/) != null) {
                    var newElement = document.createElement("b");
                    newElement.innerHTML = child.nodeValue;
                    parentNode.insertBefore(newElement, child);
                    parentNode.removeChild(child);
                }
            }
        }
    }
</script>

</body>
</html>

但是,我应该指出,如果< br /> 包含在任何元素中,你只获得那个元素的childNodes,所以如果它是一个简单的< b> 标记您只能使用< ddb>< / ddb> < b> 中c>(那是什么,顺便说一下?)。

However, I should point out that if the <br/> is wrapped in any element, you are only getting the childNodes of that element, so if it was a simple <b> tag you would only wrap text nodes inside the <b> with <ddb></ddb> (what is that, by the way?).

你还有一个错误,你指的是 text node.textContent? node.textContent:node.innerText 但是下一行只是使用了 node.textContent ,所以我修复了它。我还将正则表达式更改为简单地匹配第一个非空格字符,如果它确实找到了一个,则将其包装起来。

You also had a bug that you were assigning text to node.textContent ? node.textContent : node.innerText but then the next line simply used node.textContent, so I fixed that. I also changed the regex to simply match the first non-whitespace character, and if it did find one, it wrapped it.

这篇关于Javascript:如何获取文本节点后面/前面的break标记并用ddb标记包装它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 16:10