javascript - 如何在换行符上自定义插入的 contentEditable 的 div?

标签 javascript html contenteditable

我有生成唯一 ID 的 generate_uuid() 函数(最初从 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>

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

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

<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>

最佳答案

你可以使用 MutationObserver检测何时添加 child 并生成动态 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>

关于javascript - 如何在换行符上自定义插入的 contentEditable 的 div?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55052621/

相关文章:

jquery - 定义元素上的光标

javascript - 在 contenteditable div 中突出显示的文本周围添加 html 标签

javascript:在另一个文件中使用一个文件中的变量

javascript - AJAX : What to do when the POST succeeds?

第一次调用 Javascript 函数时效果不佳

html - 任何不使用 HTML(contenteditable 或 designMode)的 WYSIWYG 富文本编辑器,如(新的)Google Docs?

javascript - 当用户单击链接时如何关闭响应式全屏菜单?

java - 监听所有表单提交事件并在任何其他附加事件处理程序之前执行功能

php - 如何从 HTML/PHP 中的单个 <select> 变量获取多个值?

html - 由于 div 重叠,无法单击链接