Tuesday, 17 May 2016

javascript - why i can't replace the "for Each" with "for" loop?


hey everyone(; i'm using "js" to create tabs in my html .
i guess i'm missing something, but i do not understand why i can't replace the forEach loop with for loop.
this is my 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);


and this is my html:





ONELorem 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

TWO 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

THREE 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




the forEach work great. but as you can see I comment out the for loop because it's not work.The buttons are created nicely but the select function that executed by the EventListener does not work well with the for loop.

here is the link to codepen:

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...