复制$('div')。html()期望一些特定的文本

问题描述 投票:2回答:2

基本上我必须将div的内容复制到textarea,能够在textarea中编辑它,并且更改应该保存在初始div中。

我需要阻止一个看起来像data-bind: "some stuff;"的属性,并且可以为初始包装器div的子项设置,并在textarea中显示注释。

到目前为止,这是我所拥有的,遗憾的是没有任何线索如何在获取HTML时排除文本。 https://jsfiddle.net/2kduy9vp/112/

$('.editor').html($('.main').html());

$('.editor').on('input propertychange', function(){
	$('.main').html($(this).val());
});
.editor {
  width: 100%;
  height: 500px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
  <!-- I'm a comment, don't copy me -->
  <div class="child" data-bind="don't copy me" style="background-color: gray; width: 250px;">
    <span> I'm gray, copy me</span>
  </div>
  <!-- I'm a comment, don't copy me -->
  <div class="child" data-bind="don't copy me" style="background-color: pink; width: 250px;">
    <span> I'm pink, copy me</span>
  </div>
</div>

<textarea class="editor"></textarea>
javascript jquery html css
2个回答
1
投票

为什么不简单地使用div并使用contenteditable="true"使其可编辑,您可以应用任何样式来显示您想要的内容:

$('.editor').html($('.main').html());

$('.editor').on('input propertychange', function() {
  $('.main').html($(this).html());
});
.editor {
  margin-top: 20px;
  ;
  width: 100%;
  height: 500px;
  padding: 50px;
}

.editor>div {
  background: #fff!important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
  <!-- I'm a comment, exclude me -->
  <div class="child" data-bind="exclude-me" style="background-color: gray; width: 250px;">
    <span> I'm gray, copy me</span>
  </div>
  <!-- I'm a comment, exclude me -->
  <div class="child" data-bind="exclude-me-too" style="background-color: pink; width: 250px;">
    <span> I'm pink, copy me</span>
  </div>
</div>

<div class="editor" contenteditable="true"></div>

0
投票

如果我理解正确,你只需要对第一个jQuery行应用一些过滤,你将.main HTML内容添加到.editor textarea。

这些正则表达式应该做的伎俩:

$('.editor').html($('.main').html()
   .replace(/<!--[\s\S]*?-->/g, "")
   .replace(/data-bind="[\s\S]*?" /g, ""));

(HTML评论regex从这里开始:Remove HTML comments with Regex, in Javascript

© www.soinside.com 2019 - 2024. All rights reserved.