如何获取内容可编辑内容的正确内容 div

how to get proper content of a contenteditable div

$('button').on('click', function(){
 let ht = $('#divstory').html();
 console.log(ht);
});
.divstory{
 background:#eee;
  min-height:54px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="divstory" id="divstory" contenteditable="true"></div>
<br>
<button>CLICK</button>

divstory里面写下:

323
525
727
第979章【=20=】

然后点击 button

结果是:

323<div>525</div><div>727</div><div>979</div><div><br></div>

为什么 323 没有 div 标签?

以及如何像这样换行:

<div>323</div>    
<div>525</div>  
<div>727</div>  
<div>979</div>  

$('button').on('click', function(){
    var html = $('#divstory').html();
    var ht = remove_HtmlTags(html);
 console.log(ht);
});

function remove_HtmlTags (html) {
            var tmp = document.createElement("DIV");
            tmp.innerHTML = html;
            return tmp.textContent || tmp.innerText || "";
        }
.divstory{
 background:#eee;
  min-height:54px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="divstory" id="divstory" contenteditable="true"></div>
<br>
<button>CLICK</button>

这是因为 contenteditable 添加:

<div><br/></div>

进入其内容

将代码更改为:

$('button').on('click', function(){    
    var ht = $('#divstory').html();
    ht = ht.replace("<br>", '');
    console.log(ht);
});

当您向 content editable div 提供输入时,它存储在单个 textNode 中,点击输入后,新文本将分配给 divElement但首先 textNode 是原样,意味着它不会改变。您可以使用以下示例手动更改它。

$('button').on('click', function(){
 let ht = $('#divstory')[0].childNodes;
 for(let child of ht){
    if(child.constructor.name === 'Text'){
      let newChild = document.createElement('div');
      newChild.textContent = child.textContent;
      $('#divstory')[0].replaceChild(newChild, child);
    }
  }
  console.log($('#divstory').html());
});
.divstory{
 background:#eee;
  min-height:54px;
  white-space: pre;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="divstory" id="divstory" contenteditable="true"></div>
<br>
<button>CLICK</button>

如果您不关心保留换行符,您可以将 .html() 替换为 .text() 到 return 只是没有 html.[=18 的文本=]

如果你想保留换行符,但又不想 return 任何 html,即你需要替换 divbr html 元素的文本换行符使用字符 /n。这是适用于控制台或 html 输出的解决方案:

$('button').on('click', function(){
 let ht = $('#divstory').html().replace(/<div>/g,"\n").replace(/<\/div>/g,"").replace(/<br>/g,"\n");
 console.log(ht);
   $("#result").text(ht);
});
.divstory{
 background:#eee;
  min-height:54px;
}
#result{
            white-space:pre;
 }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="divstory" id="divstory" contenteditable="true"></div>
<br>
<button>CLICK</button>
<br>
<div id="result"></div>