jquery删除< span>标记,同时保留其内容(并用< br>替换< div>和< p> s)

问题描述:

是否有一种很好的方法可以删除所有的SPAN标签(同时保留其中的文本)并用BR替换所有的DIV和P?使用jQuery?

is there a good way to remove all SPAN tags (while preserving the text inside of them) and replacing all DIVs and P's with BR? Using jQuery?

<div>
 <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin rutrum tincidunt urna ac dignissim. Phasellus nisi ante, pharetra at
 <span>&nbsp;lorem a, condimentum ullamcorper</span>
 <span>&nbsp;leo. Duis pharetra nulla sit amet dui feugiat luctus.</span>
</p>
<p>
 <span>Ut eget nulla pulvinar ligula tincidunt placerat ut in eros. Cras posuere eget lacus eu lacinia. Cras lacinia porta porta. In hac habitasse platea dictumst. Maecenas nibh ligula, vulputate ut suscipit congue, euismod sed nunc. Cras quis rhoncus justo, sit amet vulputate enim.</span>
</p>
</div>

我正在处理一个contentEditable问题,并且陷印某些keydowns不是一个选项,这需要完全交叉浏览器有效和issu与返回(新行),退格和删除按钮。

I am fighting a contentEditable issue and trapping certain keydowns is not an option, this needs to be completely cross browser valid and issu with both return (new lines), backspace and delete buttons.

以下是我如何设法使它工作,由Raphaels领导回答

Here's how I managed to get it working, led by Raphaels answer

        if( $(textObject).children().length > 0 ) {
            $(textObject).children().each(function() {

                if ( $(this).is("span") ) {
                    $(this).contents().unwrap();
                }
                else if ( $(this).is("div") || $(this).is("p") ) {
                    $(this).prepend('<br />').contents().unwrap();
                }

                restoreTextFormat(this);
            });
        }

我觉得这个嵌套业务可能会占用太多资源,有没有一种简洁的方式来优化这一小块代码?

I have a feeling this nesting business is maybe taking up too much resources though, is there a neat way to optimize this little block of code?