jquery删除<span>标签,同时保留其内容(并将<divs>和<p>:s替换为<)</p> </divs> </span>

时间:2013-10-23 16:26:39

标签: javascript jquery html replace edit

是否有一种很好的方法可以删除所有SPAN标记(同时保留其中的文本)并用BR替换所有DIV和P?使用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不是一个选项,这需要完全跨浏览器有效并且发送包含return(新行),退格键和删除按钮。

5 个答案:

答案 0 :(得分:5)

这是我如何设法让它工作,由Raphaels回答

        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);
            });
        }

我有一种感觉,这种嵌套业务可能占用了太多资源,有没有一种巧妙的方法来优化这一小块代码?

答案 1 :(得分:2)

你可能会做那样的事情

//remove all span tags, keeping the content
$('span').contents().unwrap();
//add a br at the start of each p or div, then remove p or div 
//use append instead of prepend to add the  line break at the end, not at the start.
$('p, div').prepend('<br />')
           .contents().unwrap();

请参阅jsFiddle

答案 2 :(得分:2)

使用基本VanillaJS

// this function does the hard work for us
function unwrap(root,tagname,extra) {
    var elms = root.getElementsByTagName(tagname), l = elms.length, i;
    for( i=l-1; i>=0; i--) {
        // work backwards to avoid possible complications with nested spans
        while(elms[i].firstChild)
            elms[i].parentNode.insertBefore(elms[i].firstChild,elms[i]);
        if( extra) extra(elms[i]);
        elms[i].parentNode.removeChild(elms[i]);
    }
}

// assumes "container" is a pointer to your container, such as from
// using document.getElementById('container') or similar
unwrap(container,"span"); // remove all spans, preserving their content
unwrap(container,"div",function(elm) {
    elm.parentNode.insertBefore(document.createElement('br'),elm);
});
unwrap(container,"p",function(elm) {
    elm.parentNode.insertBefore(document.createElement('br'),elm);
});

希望这有帮助!

答案 3 :(得分:-2)

请尝试添加名为parent的div并编辑html。

$(this).find('#parent').html($(this).find('#parent').html().replace('<div>', '').replace('</div>', '<br/>').replace('<p>', '').replace('</p>', '<br/>').replace('<span>', '').replace('</span>', ''));

这可能会解决您的目的。 Atleast给你一个想法。

答案 4 :(得分:-2)

添加样式显示:inline-block;为了contenteditable,它不会在chrome中自动生成div,p,span

相关问题