3

すべての SPAN タグを (テキストを保持したまま) 削除し、すべての DIV と P を BR に置き換える良い方法はありますか? 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 の問題と戦っていますが、特定のキーダウンをトラップすることはオプションではありません。これは完全にクロス ブラウザーで有効であり、リターン (改行)、バックスペース、および削除ボタンの両方で発行する必要があります。

4

5 に答える 5

5

ラファエルの答えに導かれて、どうにかしてそれを機能させることができた方法は次のとおりです

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

このネスティング ビジネスがリソースを使いすぎているように感じますが、この小さなコード ブロックを最適化する適切な方法はありますか?

于 2013-10-24T15:46:16.653 に答える
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);
});

お役に立てれば!

于 2013-10-23T16:58:38.813 に答える
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を参照してください

于 2013-10-23T16:45:49.233 に答える
-2

スタイルを追加 display:inline-block; contenteditable にすると、chrome で自動で div、p、span が生成されなくなります

于 2014-07-11T02:53:08.503 に答える