嘿大家(;我正在使用“js”在我的HTML中创建标签。
我想我错过了什么,但我不明白为什么我不能用 for 循环替换 forEach 循环。
这是我的js:
var divsList = [];
var div = document.createElement("div");
function asTabs(container) {
for (var i = 0; i < container.childNodes.length; i++) {
var child = container.childNodes[i];
if (child.nodeType === document.ELEMENT_NODE) {
divsList.push(child);
}
}
console.log(divsList);
divsList.forEach(function (tab, i) {
var button = document.createElement("button");
button.textContent = divsList[i].getAttribute("data-tabname");
button.addEventListener("click", function () {
select(i);
});
div.appendChild(button);
});
container.insertBefore(div, container.firstChild);
}
/*for (var i = 0; i < divsList.length; i++) {
var button = document.createElement("button");
button.textContent = divsList[i].getAttribute("data-tabname");
button.addEventListener("click", function () {
select(i);
});
div.appendChild(button);
}
container.insertBefore(div, container.firstChild);
console.log(container);
}*/
function select(n) {
for (var i = 0; i < divsList.length; i++) {
divsList[i].id = "Tab";
if (n === i) {
divsList[i].style.display = "";
div.childNodes[i].style.background = "#FBFBFB";
} else {
divsList[i].style.display = "none";
div.childNodes[i].style.background = "";
}
}
}
asTabs(document.querySelector("#wrapper"));
select(0);
这是我的HTML:
<div id="wrapper">
<div data-tabname="one"><span>ONE</span>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean in porta augue. Proin iaculis turpis eget orci commodo, id aliquam nisi eleifend. Nulla nec gravida nibh, sed dapibus lorem. Cras non tempus erat, sed </div>
<div data-tabname="two"><span>TWO</span> Quisque pellentesque lacus sollicitudin arcu hendrerit euismod. Proin sed quam rutrum, dapibus dolor sed, blandit lorem. Quisque sed libero et eros vehicula lobortis. Mauris eleifend scelerisque mollis. Quisque mollis nibh dui, quis blandit ligul</div>
<div data-tabname="three"><span>THREE</span> Sed lorem mi, pellentesque eget porta at, viverra at ex. Quisque viverra eu lorem a tempor. Donec ultrices ullamcorper elementum. Vivamus ut varius mauris. Suspendisse nisi
</div>
</div>
forEach 工作得很好。但正如你所看到我注释掉 for 循环,因为它不起作用。按钮创建得很好但选择函数由 EventListener执行与 for 循环不兼容。
here is the link to codepen: