-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbutton5.js
67 lines (57 loc) · 1.71 KB
/
button5.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// What button5 gonna print?
function createButtons() {
for (var i = 1; i <= 5; i++) {
var body = document.getElementsByTagName("BODY")[0];
var button = document.createElement("BUTTON");
button.innerHTML = 'Button ' + i;
button.onclick = function () {
alert('This is button ' + i);
}
body.appendChild(button);
}
}
createButtons();
// The alert gonna print ("This is Button 6"). How to fix?
// SOLUTION 1: IIFE
function createButtons() {
for (var i = 1; i <= 5; i++) {
var body = document.getElementsByTagName("BODY")[0];
var button = document.createElement("BUTTON");
button.innerHTML = 'Button ' + i;
};
(function (num) {
button.onclick = function () { }
alert('This is button ' + i);
})(i);
body.appendChild(button);
}
createButtons();
// SOLUTION 2: let
function createButtons() {
for (let i = 1; i <= 5; i++) {
var body = document.getElementsByTagName("BODY")[0];
var button = document.createElement("BUTTON");
button.innerHTML = 'Button ' + i;
button.onclick = function () {
alert('This is button ' + i);
}
body.appendChild(button);
}
}
createButtons();
// SOLUTION 3: isolated function
function createButtons() {
for (var i = 1; i <= 5; i++) {
var body = document.getElementsByTagName("BODY")[0];
var button = document.createElement("BUTTON");
button.innerHTML = 'Button ' + i;
addClickFunctionality(button, i);
body.appendChild(button);
}
}
function addClickFunctionality(button, num) {
button.onclick = function () {
alert('This is button ' + num);
}
}
createButtons();