jquery删除标签,同时保留其内容(并用替换和:s)

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

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin rutrum tincidunt urna ac dignissim. Phasellus nisi ante, pharetra at  lorem a, condimentum ullamcorper  leo. Duis pharetra nulla sit amet dui feugiat luctus.

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.

我正在打一个contentEditable问题并且捕获某些keydowns不是一个选项,这需要完全跨浏览器有效并且issu包含return(新行),退格键和删除按钮。

这是我设法让它工作的方式,由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('
').contents().unwrap(); } restoreTextFormat(this); }); }

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

你可能会做那样的事情

 //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('
') .contents().unwrap();

见jsFiddle

使用基本的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); }); 

希望这可以帮助!

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

 $(this).find('#parent').html($(this).find('#parent').html().replace('
', '').replace('
', '
').replace('

', '').replace('

', '
').replace('', '').replace('', ''));

这可能会解决您的目的。 Atleast给你一个主意。

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