Bonjour,
J'ai cru avoir appris qu'une variable déclaré avec let est locale, et celle créée avec var est global.
J'ai une condition if, dans laquelle j'ai créé une variable let pour faire un calcul
Code javascript : Sélectionner tout - Visualiser dans une fenêtre à part
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 if($(this).hasClass("hasChildren")){ $(this).attr("style","border:2px solid blue !important"); let a = $(this).first().children('div').first().children('a:first-child').attr("style","border:1px solid yellow !important"); } else{ let a = $(this).first().children('div').first().children('a').attr("style","border:10px solid white !important"); let a_padding = Math.ceil((a.outerWidth() - a.width()) - (a.outerWidth() - a.innerWidth())); let a_border = Math.ceil(a.outerWidth() - a.innerWidth()); let a_wwidth = Math.ceil(a.width()); let a_paddingBorder = a_padding + a_border; let a_width = a_wwidth + a_border; console.log("a_padding:", a_padding); console.log("a_border:", a_border); console.log("a_widthWithoutBorder:", a_wwidth); console.log("div_paddingBorder:", a_paddingBorder); console.log("a_width:", a_width); console.log("----------"); } console.log(a_width);
Dans ce cas, mon console.log ne va rien afficher, alors que console.log("a_width:", a_width); va afficher un résultat
Donc j'ai modifié comme cela
Pourquoi ceci m'affiche un résultat
Code : Sélectionner tout - Visualiser dans une fenêtre à part
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 var a_width =1; if($(this).hasClass("hasChildren")){ $(this).attr("style","border:2px solid blue !important"); let a = $(this).first().children('div').first().children('a:first-child').attr("style","border:1px solid yellow !important"); } else{ let a = $(this).first().children('div').first().children('a').attr("style","border:10px solid white !important"); let a_padding = Math.ceil((a.outerWidth() - a.width()) - (a.outerWidth() - a.innerWidth())); let a_border = Math.ceil(a.outerWidth() - a.innerWidth()); let a_wwidth = Math.ceil(a.width()); let a_paddingBorder = a_padding + a_border; a_width = a_wwidth + a_border; console.log("a_padding:", a_padding); console.log("a_border:", a_border); console.log("a_widthWithoutBorder:", a_wwidth); console.log("div_paddingBorder:", a_paddingBorder); console.log("a_width:", a_width); console.log("----------"); } menu[index] = { index: index, div_padding: div_padding, div_border: div_border, div_paddingBorder: div_paddingBorder, a_width: a_width, w_total: div_paddingBorder + a_width, name:"li-"+index }; }); console.log(menu);
console.log("a_width:", a_width); alors que dans console.log(menu); il m'affiche
Le fait d'avoir fait ceci var a_width =1; n'est-ce pas suffisant pour que la variable soit globale?a_width: undefined
Pierre
Partager