如何在换行符上自定义插入的内容divEditable?

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

我有generate_uuid()函数生成唯一ID(最初从here检索):

function generate_uuid() {
  return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c =>
    (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
  )
}

我有contentEditable div

<div contenteditable>
  <div id="48b62163-9f3b-4b20-8dad-dc99e27e1243">Edit text content here.<div>
</div>

当我向文本内容添加新行时,html代码变为:

<div contenteditable>
  <div id="48b62163-9f3b-4b20-8dad-dc99e27e1243">Edit text content here.<div>
  <div id="48b62163-9f3b-4b20-8dad-dc99e27e1243">New line 1.</div>
</div>

正如我们注意到的那样,新的div与之前存在的div相同。

当我添加更多行时,html代码变为:

<div contenteditable>
  <div id="48b62163-9f3b-4b20-8dad-dc99e27e1243">Edit text content here.<div>
  <div id="48b62163-9f3b-4b20-8dad-dc99e27e1243">New line 1.</div>
  <div id="48b62163-9f3b-4b20-8dad-dc99e27e1243">New line 2.</div>
  <div id="48b62163-9f3b-4b20-8dad-dc99e27e1243">New line 3.</div>
</div>

同样,新的divs与之前存在的div相同。

每次用户点击换行符时,我如何自定义新插入的divs?我想通过id函数生成新插入的divgenerate_uuid()属性。这样的事情应该是结果:

<div contenteditable>
  <div id="48b62163-9f3b-4b20-8dad-dc99e27e1243">Edit text content here.<div>
  <div id="0b0e3518-1fb2-43e4-9160-6563ac0f82be">New line 1.</div>
  <div id="57d399c6-afa0-42ae-83c2-d6d7937f22d3">New line 2.</div>
  <div id="1fe51cac-bb79-47e2-bd95-e813b33e29aa">New line 3.</div>
</div>
javascript html contenteditable
1个回答
2
投票

您可以使用MutationObserver来检测添加子项的时间并生成动态ID:

function uuid() {
  return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c =>
    (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
  )
}

function subscriber(mutations) {
  mutations.forEach(mutation => {
    mutation.addedNodes.forEach(node => node.id = uuid());
    console.clear();
    console.log([...mutation.target.children].map(x => x.id));
  });
}

const observer = new MutationObserver(subscriber);
observer.observe(document.querySelector('div[contenteditable]'), { childList: true });
<div contenteditable>
  <div id="48b62163-9f3b-4b20-8dad-dc99e27e1243">Edit text content here.<div>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.