Javascript 如何为打开设计模式的父div中新创建的div提供id
就好像我们用它创建了一个div元素Javascript 如何为打开设计模式的父div中新创建的div提供id,javascript,php,html,Javascript,Php,Html,就好像我们用它创建了一个div元素contenteditable=“true”,然后如果在控制台中看到它,那么 第一。在控制台中有一个简单的div标记 <div id="typbody" contenteditable="true" style="width:100%; height:200px; border:1px solid #ccc; "></div> 第二。如果我在div标签中按enter键,那么在控制台中它将被写入 如果我在里面写任何东西,它也写在里面
contenteditable=“true”
,然后如果在控制台中看到它,那么
第一。在控制台中有一个简单的div标记
<div id="typbody" contenteditable="true" style="width:100%; height:200px; border:1px solid #ccc; "></div>
第二。如果我在div标签中按enter键,那么在控制台中它将被写入
如果我在里面写任何东西,它也写在
里面
所以我的问题是:
1) 有没有办法给这些新创建的div
标签一个id?2) 是否有任何方法可以为所有新的
div
提供不同的ID或类
除了
javascript
或php
,我还需要学习其他语言吗 创建id时添加id。如果希望它是动态的,只需将id变量设置为动态的
var frag = document.createDocumentFragment(),
var item = document.createElement('div');
item.id = whatever;
frag.appendChild(item);
然后将碎片插入到DOM中的任意位置。例如,在元素“foo”之后:
foo.parentNode.insertBefore(frag, foo.nextSibling);
div
标记一个id?”你已经尝试过什么?在“设计模式开启”下你是什么意思?
就是这么多!如果您试图手动更改登录到控制台的元素的id,请用鼠标右键单击它,然后选择“在元素面板中显示”,然后再次单击并选择“添加属性”或“编辑属性”。(在Google Chrome中,在其他浏览器中也可能类似)但是,如果您使用javascript创建这个“新div元素”,为什么不在创建它的同时添加id属性呢?
(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);
}
}());
#typbody > div:nth-child(odd) {
color: green;
}
#typbody > div:nth-child(even) {
color: blue;
}