2016-05-31 43 views
-1

我使用<div contenteditable="true">,当我按空格输入换行符时,它会生成<div><br></div>。 但我只是想从开始和结束时删除它。有效的方法来删除空格

例如:

<div contenteditable="true">

<div><br></div>我想删除这个

ABC

<div><br></div>保持

<div><br></div>我想删除这个

<div><br></div>我想删除这个

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

目前我使用两个循环删除它,但我正在寻找一个更好的方式来过滤它。 任何人都可以引导我?

谢谢。

+0

在要删除它们什么样的行动?任何“点击事件”,“模糊事件”等? –

+0

单击事件.... – hendry91

回答

0

你可以用while循环代替for循环实现它。您需要存储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里面是空的。(你的问题指出)....

这可能有助于.....

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

此代码删除的div是空的...如果多数民众赞成你想这可能有所帮助

+0

但我只想删除文本之前和最后一个文本之后的空div。 – hendry91