Skip to content

Instantly share code, notes, and snippets.

@newnewcoder
Last active July 19, 2019 01:42
Show Gist options
  • Save newnewcoder/75983680975d63fdd72b3c8c3dc9780b to your computer and use it in GitHub Desktop.
Save newnewcoder/75983680975d63fdd72b3c8c3dc9780b to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<body>
<div id="container"></div>
<script>
var node1 = document.createElement("p");
var txt1 = document.createTextNode("This is 1 ");
node1.appendChild(txt1);
var node2 = document.createElement("p");
var txt2 = document.createTextNode("This is 2 ");
node2.appendChild(txt2);
var node3 = document.createElement("p");
var txt3 = document.createTextNode("This is 3 ");
node3.appendChild(txt3);
var node4 = document.createElement("p");
var txt4 = document.createTextNode("This is 4 ");
node4.appendChild(txt4);
var element = document.getElementById("container");
element.appendChild(node1);
element.appendChild(node2);
element.appendChild(node3);
element.appendChild(node4);
var addHandlers = function(nodes) {
var i;
for (i = 0; i < nodes.length; i += 1) {
(function(j) {
nodes[j].onclick = function(e) {
console.log(j);
}
})(i);
}
}
/*
// wrong
var addHandlers = function(nodes) {
var i;
for (i = 0; i < nodes.length; i += 1) {
nodes[i].onclick = function(e) {
console.log(i);
}
}
}
*/
/*
//OK
var addHandlers = function(nodes) {
for (let i = 0; i < nodes.length; i += 1) {
nodes[i].onclick = function(e) {
console.log(i);
}
}
}
*/
_nodes = [node1, node2, node3, node4];
addHandlers(_nodes);
console.log(_nodes);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment