2016-05-31 12 views
-1

私は<div contenteditable="true">を使用しています。空の入力で改行を入力すると、<div><br></div>が生成されます。 しかし、私はちょうどそれを最初から最後まで削除したい。例えば空のdivを効率的に削除する

<div contenteditable="true">

<div><br></div>私は

<div><br></div>

残るこの

ABCを削除したいです私は現在、私はそれを削除するには、ループ2を使用しています、しかし、私はより良いを探しています私はこの

</div>

for(var x = item.length - 1 ; x >= 0 ; x--){ 
    if($(item[x]).html() == "<br>"){ 
     $(item[x]).remove(); 
    }else{ 
     break; 
    } 
} 

for(var x = 0; x <= item.length-1 ; x++){ 
    if($(item[x]).html() == "<br>"){ 
     $(item[x]).remove(); 
    }else{ 
     break; 
    } 
} 

を削除したいこの

<div><br></div>を削除したい

<div><br></div>それをフィルタリングする方法。 誰でも私を導くことができますか?

ありがとうございました。これは役立つかもしれ

あなたが空であるdiv要素を削除したい場合は

+0

?任意の「クリックイベント」、「ブラーイベント」など? –

+0

clickイベント.... – hendry91

答えて

0

実際にはループforではなくループwhileで実現できます。 firstlastの参照番号をcontenteditabledivに格納し、それをループのwhileループで操作する必要があります。コードの周りのコメントの詳細な説明。あなたがそれらを削除したいアクションに

$('.remove').on('click', function() { 
 
    var firstChild = $('div[contenteditable] div:first'); 
 
    var lastChild = $('div[contenteditable] div:last'); 
 
    //store the reference for first and last child of the contenteditable div 
 
    while(firstChild.html()=="<br>")//remove all the element's until firstchild's html!="<br>" i.e. is not empty 
 
    { 
 
    firstChild.remove();//remove it 
 
    firstChild= $('div[contenteditable] div:first'); //again store the reference to new first child after remove 
 
    } 
 
    //same goes with last child 
 
    while(lastChild.html()=="<br>") 
 
    { 
 
    lastChild.remove(); 
 
    lastChild= $('div[contenteditable] div:last'); 
 
    } 
 
})
div[contenteditable] { 
 
    background-color: orange; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div contenteditable="true"> 
 

 
</div> 
 
<button type="button" class="remove">Remove unwanted</button>

+0

ありがとう、私は新鮮な卒業生、まだ別の方法とより良い方法でコードを学ぶ:D – hendry91

+0

いつでも..ハッピーコーディング.. :) –

0

...(あなたの質問状態).... .....

$("div:empty").remove(); 

このコードはdiv要素を取り除くこと空の場合...これが助けてくれるものであれば

+0

しかし、私はテキストの前と最後のテキストの後に空のdivを削除したいだけです。 – hendry91

関連する問題