就好像我们用它制作一个 div 元素 contenteditable="true"
然后如果在控制台中看到这一点,则
第一。在控制台中有一个简单的 div 标签。
<div id="typbody" contenteditable="true" style="width:100%; height:200px; border:1px solid #ccc; "></div>
第二。如果我在 div 标签中按 Enter 键,那么在控制台中它会写为 <div><br></div>
!
如果我在里面写任何东西,它也会写在 <div>
里面.
所以我的问题是:
1)有什么办法可以给这些新创建的div
标记一个 ID?
2)还有什么方法可以为所有新的div
提供不同的ID或类别吗?的?
除了 javascript
之外我还需要学习其他语言吗?或php
?
最佳答案
- “有什么方法可以为这些新创建的
div
标签提供 id 吗?” - “还有什么方法可以为所有新的 div 提供不同的 id 或类吗?”
是的,有!
看看MutationObserver MDN , 和 DOM MutationObserver – reacting to DOM changes without killing browser performance.
(function () {
"use strict";
var target = document.getElementById("typbody"),
config = {
childList: true,
},
eCollection = [],
i = 0,
id = target.id + "_",
observer = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
if (mutation.addedNodes) {
[].forEach.call(mutation.addedNodes, function (node) {
if (node.nodeName.toLowerCase() === "div") {
var index = eCollection.indexOf(node.nextSibling);
node.id = id + i++;
eCollection.push(node);
if (node.nextSibling && index > -1) {
node.id = node.nextSibling.id;
for (var j = index; j < eCollection.length - 1; j++) {
eCollection[j].id = id + (+eCollection[j].id.substr(id.length) + 1);
}
}
eCollection.sort(sortC);
}
});
}
if (mutation.removedNodes) {
[].forEach.call(mutation.removedNodes, function (node) {
if (node.nodeName.toLowerCase() === "div") {
var index = eCollection.indexOf(node);
eCollection.splice(index, 1);
for (var j = index; j < eCollection.length; j++) {
eCollection[j].id = id + (eCollection[j].id.substr(id.length) - 1);
}
i--;
eCollection.sort(sortC);
}
});
}
});
});
observer.observe(target, config);
function sortC(a, b) {
return a.id.substr(id.length) - b.id.substr(id.length);
}
}());
但是为什么你想要这样的行为?
如果您想向这些元素添加一些样式,为什么不简单地使用 css:
#typbody > div:nth-child(odd) {
color: green;
}
#typbody > div:nth-child(even) {
color: blue;
}
关于javascript - 如何在设计模式打开的情况下为父 div 内新创建的 div 提供 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21529323/