Programmation Web : DOM / JavaScript
description
Transcript of Programmation Web : DOM / JavaScript
Programmation Web :Programmation Web :DOM / JavaScriptDOM / JavaScript
Jérôme CUTRONAJérôme CUTRONA
[email protected]@univ-reims.fr
08:06:0708:06:07 Programmation Web 2013-2014Programmation Web 2013-2014 11
DOM = Document Object ModelDOM = Document Object Model
API (Application Programming Interface) pour la API (Application Programming Interface) pour la manipulation de HTML / XMLmanipulation de HTML / XML
Définit la structure logique des documentsDéfinit la structure logique des documents Définit la façon d’y accéder, de la manipulerDéfinit la façon d’y accéder, de la manipuler
Créer des documentsCréer des documentsParcourir leur structureParcourir leur structureAjouter, effacer, modifier des élémentsAjouter, effacer, modifier des élémentsAjouter, effacer, modifier leur contenuAjouter, effacer, modifier leur contenu
2208:06:0808:06:08 Programmation Web 2013-2014Programmation Web 2013-2014
Qu’est-ce que le DOM ?Qu’est-ce que le DOM ?
<<tabletable>>
<<tbodytbody>>
<<trtr><><tdtd>>AA</</tdtd>>
<<tdtd>>BB</</tdtd>>
</</trtr>>
<<trtr><><tdtd>>CC</</tdtd>>
<<tdtd>>DD</</tdtd>>
</</trtr>>
</</tbodytbody>>
</</tabletable>>
3308:06:0808:06:08 Programmation Web 2013-2014Programmation Web 2013-2014
A
td
B
td
tr
C
td
D
td
tr
tb o dy
ta b le
Qu’est-ce que le DOM ?Qu’est-ce que le DOM ?
Représentation arborescente du documentReprésentation arborescente du document Modèle objet (structure + méthodes)Modèle objet (structure + méthodes) Permet la manipulation du documentPermet la manipulation du document Une implémentation : JavaScript…Une implémentation : JavaScript… … … Des implémentations :Des implémentations :
JavaScript IEJavaScript IE JavaScript Mozilla / FirefoxJavaScript Mozilla / Firefox JavaScript OperaJavaScript Opera ……
4408:06:0808:06:08 Programmation Web 2013-2014Programmation Web 2013-2014
JavaScript : PrincipeJavaScript : Principe
Langage de script objetLangage de script objet Syntaxe style C / C++ / JavaSyntaxe style C / C++ / Java Sensible à la casseSensible à la casse N’est PAS du JavaN’est PAS du Java Exécuté par le client WebExécuté par le client Web Peut être désactivé sur le clientPeut être désactivé sur le client Nombreux objets pour la manipulation HTMLNombreux objets pour la manipulation HTML Gestion des événements HTMLGestion des événements HTML Rendre les pages dynamiques (HTML+CSS+JS)Rendre les pages dynamiques (HTML+CSS+JS) Haut niveau d’incompatibilité…Haut niveau d’incompatibilité…
5508:06:0808:06:08 Programmation Web 2013-2014Programmation Web 2013-2014
JavaScript : ExempleJavaScript : Exemple
<<htmlhtml>> <<headhead>> <<titletitle>>Ma première page WebMa première page Web</</titletitle>> </</headhead>> <<bodybody>> <<scriptscript typetype=="text/javascript""text/javascript" languagelanguage=="JavaScript""JavaScript">>
<!--<!-- document.writeln(document.writeln("Salut !""Salut !") ;) ; // -->// --> </</scriptscript>></</bodybody>></</htmlhtml>>
6608:06:0808:06:08 Programmation Web 2013-2014Programmation Web 2013-2014
Structures conditionnellesStructures conditionnelles
ifif ((conditioncondition))
{{
instructions ;instructions ;
}}
[ [ elseelse
{{
instructions ;instructions ;
} } ]]
7708:06:0808:06:08 Programmation Web 2013-2014Programmation Web 2013-2014
Structures conditionnellesStructures conditionnelles
switchswitch ((expressionexpression))
{{ casecase étiquetteétiquette ::
instructions ;instructions ; breakbreak ; ; casecase étiquetteétiquette ::
instructions ;instructions ; breakbreak ; ; defaultdefault ::
instructions ;instructions ;}}
8808:06:0808:06:08 Programmation Web 2013-2014Programmation Web 2013-2014
Structures itérativesStructures itératives
whilewhile ((conditioncondition))
{{
instructions ;instructions ;
}}
dodo
{{
instructions ;instructions ;
}}
whilewhile ((conditioncondition)) ; ;9908:06:0808:06:08 Programmation Web 2013-2014Programmation Web 2013-2014
Structures itérativesStructures itératives
forfor ((instr ;instr ; condition ; instrcondition ; instr))
{ { instructions ; instructions ; }}
forfor ((variable variable inin objet|tableau objet|tableau))
{ { instructions ; instructions ; }}
for eachfor each ((variable variable inin objet|tableau objet|tableau))
{ { instructions ; instructions ; }}
101008:06:0808:06:08 Programmation Web 2013-2014Programmation Web 2013-2014
CommentairesCommentaires
// Commentaire ligne// Commentaire ligne
/* Commentaire multi-lignes *//* Commentaire multi-lignes */
111108:06:0808:06:08 Programmation Web 2013-2014Programmation Web 2013-2014
VariablesVariables
DéclarationDéclaration de variables de variables facultativefacultative Variables Variables non typées à la déclarationnon typées à la déclaration
varvar nom_variablenom_variable ; ; Typage dynamique Typage dynamique à l’affectation :à l’affectation :
Nombres (Nombres (42, 3.1442, 3.14)) Booléens (Booléens (truetrue, , falsefalse)) Chaînes (Chaînes ("Salut !""Salut !", , 'Salut !' 'Salut !' )) nullnull undefinedundefined FonctionsFonctions ObjetsObjets
121208:06:0808:06:08 Programmation Web 2013-2014Programmation Web 2013-2014
Typage des variables à l’affectationTypage des variables à l’affectation
varvar v ; v ;
windowwindow.alert.alert(("Type de ""Type de " + v + + v + " : "" : " + + typeoftypeof v v)) ; ;
v = v = 1212 ; ;
windowwindow.alert.alert(("Type de ""Type de " + v + + v + " : "" : " + + typeoftypeof v v)) ; ;
v = v = 1212..4242 ; ;
windowwindow.alert.alert(("Type de ""Type de " + v + + v + " : "" : " + + typeoftypeof v v)) ; ;
v = v = 'hello''hello' ; ;
windowwindow.alert.alert(("Type de ""Type de " + v + + v + " : "" : " + + typeoftypeof v v)) ; ;
v = v = truetrue ; ;
windowwindow.alert.alert(("Type de ""Type de " + v + + v + " : "" : " + + typeoftypeof v v)) ; ;
v = v = nullnull ; ;
windowwindow.alert.alert(("Type de ""Type de " + v + + v + " : "" : " + + typeoftypeof v v)) ; ;
v = v = functionfunction ((aa)) {{ returnreturn a+ a+1212 ; ; }} ; ;
windowwindow.alert.alert(("Type de ""Type de " + v + + v + " : "" : " + + typeoftypeof v v)) ; ;
v = v = {{ a: a:1212, b:, b:'attr''attr' }} ; ;
windowwindow.alert.alert(("Type de ""Type de " + v + + v + " : "" : " + + typeoftypeof v v)) ; ;
131308:06:0808:06:08 Programmation Web 2013-2014Programmation Web 2013-2014
undefinedundefinedundefinedundefined
numbernumbernumbernumber
numbernumbernumbernumber
stringstringstringstring
booleanbooleanbooleanboolean
objectobjectobjectobject
functionfunctionfunctionfunction
objectobjectobjectobject
Fonctions : définition classiqueFonctions : définition classique
Valeur de retour non typéeValeur de retour non typée Paramètres non typésParamètres non typés
// Définition :// Définition :
functionfunction ma_fonctionma_fonction((argumentsarguments))
{{
instructions ;instructions ;
returnreturn quelque_chose; quelque_chose; // ou pas… // ou pas…
}}
// Appel :// Appel :
ma_fonctionma_fonction((1212)) ; ;141408:06:0808:06:08 Programmation Web 2013-2014Programmation Web 2013-2014
Fonctions : variable et affectationFonctions : variable et affectation
Fonction est un type de variableFonction est un type de variable
functionfunction f f((aa)) { { returnreturn a + a ; a + a ; }}
varvar g = g = functionfunction ((aa)) { { returnreturn a * a ; a * a ; }} ; ;
functionfunction h h((a, une_fonctiona, une_fonction)) {{ returnreturn une_fonction une_fonction((aa)) ; ;}}
windowwindow.alert.alert(("f(42) : ""f(42) : " + f + f(42))(42)) ; ;windowwindow.alert.alert(("g(12) : ""g(12) : " + g + g(12))(12)) ; ;windowwindow.alert.alert(("h(12, g) : ""h(12, g) : " + h + h(12(12, g, g)))) ; ;windowwindow.alert.alert(("h(12, f) : ""h(12, f) : " + h + h(12(12, f, f)))) ; ;
151508:06:0808:06:08 Programmation Web 2013-2014Programmation Web 2013-2014
84848484
144144144144
14414414414424242424
Fonctions : variable et affectationFonctions : variable et affectation
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><<htmlhtml>> <<headhead>> <<metameta http-equivhttp-equiv=="Content-Type""Content-Type" contentcontent=="text/html; charset=utf-8""text/html; charset=utf-8">> <<titletitle>>Les fonctions sont un type de variableLes fonctions sont un type de variable</</titletitle>> <<scriptscript typetype=='text/javascript''text/javascript'>> // Au chargement complet du document// Au chargement complet du document windowwindow.onload = .onload = functionfunction()() {{ varvar bouton = bouton = documentdocument.forms.forms[['formu''formu']].elements.elements[['btn''btn']] ; ; bouton.onclick = bouton.onclick = functionfunction()() { { windowwindow..alertalert(('Click''Click')) ; ; }} }} </</scriptscript>> </</headhead>> <<bodybody>> <<formform namename=='formu''formu'>> <<inputinput typetype=='button''button' namename=='btn''btn' valuevalue=='Cliquez''Cliquez'>> </</formform>> </</bodybody>></</htmlhtml>>
161608:06:0808:06:08 Programmation Web 2013-2014Programmation Web 2013-2014
https://iut-info.univ-reims.fr/users/cutrona/exemplesS4/fonctions2.htmlhttps://iut-info.univ-reims.fr/users/cutrona/exemplesS4/fonctions2.html
Portée des variablesPortée des variables
La La portée des variables est liée aux fonctions portée des variables est liée aux fonctions et et non aux blocs non aux blocs ifif, , whilewhile, etc., etc.
Les variables sont Les variables sont globalesglobales si si déclarées hors de toute fonctiondéclarées hors de toute fonction déclarées dans une fonction SANS le mot clé déclarées dans une fonction SANS le mot clé varvar
Les variables sont Les variables sont locales à une fonction locales à une fonction sisi déclarées dans une fonction AVEC le mot clé déclarées dans une fonction AVEC le mot clé varvar
Les variables sont accessiblesLes variables sont accessibles après la déclarationaprès la déclaration après la première affectationaprès la première affectation
171708:06:0808:06:08 Programmation Web 2013-2014Programmation Web 2013-2014
Portée des variables : illustrationPortée des variables : illustration
varvar a = a = 'contenu variable a''contenu variable a' ; ;functionfunction f f()() {{ b = b = 'contenu variable b''contenu variable b' ; ; varvar c = c = 'contenu variable c''contenu variable c' ; ; windowwindow.alert.alert(("Dans f() a est de type ""Dans f() a est de type " + + typeoftypeof a a)) ; ; windowwindow.alert.alert(("Dans f() b est de type ""Dans f() b est de type " + + typeoftypeof b b)) ; ; windowwindow.alert.alert(("Dans f() c est de type ""Dans f() c est de type " + + typeoftypeof c c)) ; ; windowwindow.alert.alert(("Dans f() i est de type ""Dans f() i est de type " + + typeoftypeof i i)) ; ;}}functionfunction g g()() {{ forfor ((varvar i= i=00; i<; i<11; i++; i++)) { { documentdocument.write.write((ii)) ; ; }} windowwindow.alert.alert(("Dans g() a est de type ""Dans g() a est de type " + + typeoftypeof a a)) ; ; windowwindow.alert.alert(("Dans g() b est de type ""Dans g() b est de type " + + typeoftypeof b b)) ; ; windowwindow.alert.alert(("Dans g() c est de type ""Dans g() c est de type " + + typeoftypeof c c)) ; ; windowwindow.alert.alert(("Dans g() i est de type ""Dans g() i est de type " + + typeoftypeof i i)) ; ;}}windowwindow.alert.alert(("Au niveau global a est de type ""Au niveau global a est de type " + + typeoftypeof a a)) ; ;windowwindow.alert.alert(("Au niveau global b est de type ""Au niveau global b est de type " + + typeoftypeof b b)) ; ;windowwindow.alert.alert(("Au niveau global c est de type ""Au niveau global c est de type " + + typeoftypeof c c)) ; ;windowwindow.alert.alert(("Au niveau global i est de type ""Au niveau global i est de type " + + typeoftypeof i i)) ; ;ff()() ; ;gg()() ; ;
181808:06:0808:06:08 Programmation Web 2013-2014Programmation Web 2013-2014
stringstringstringstring
undefinedundefinedundefinedundefined
undefinedundefinedundefinedundefined
undefinedundefinedundefinedundefined
stringstringstringstring
stringstringstringstring
stringstringstringstring
undefinedundefinedundefinedundefined
stringstringstringstring
stringstringstringstring
undefinedundefinedundefinedundefined
numbernumbernumbernumber
https://iut-info.univ-reims.fr/users/cutrona/exemplesS4/portee.html
https://iut-info.univ-reims.fr/users/cutrona/exemplesS4/portee.html
Fermetures (closures)Fermetures (closures)
PortéePortée des variables des variables d’une fonction d’une fonction étendueétendue : : aux fonctions définies dans une fonctionaux fonctions définies dans une fonction aux fonctions définies dans les fonctions définies aux fonctions définies dans les fonctions définies
dans une fonctiondans une fonction aux fonctions définies dans les fonctions définies aux fonctions définies dans les fonctions définies
dans les fonctions définies dans une fonctiondans les fonctions définies dans une fonction ……
Une fonction peut accéder aux Une fonction peut accéder aux variables de son variables de son contexte contexte et aux variables des et aux variables des contextes parentscontextes parents
La capture des variables se fait à la fin de La capture des variables se fait à la fin de l’appel de la fonction contenant les déclarationsl’appel de la fonction contenant les déclarations
191908:06:0808:06:08 Programmation Web 2013-2014Programmation Web 2013-2014
Fermetures : exempleFermetures : exemple
functionfunction f f()() {{ // Variable a locale à f()// Variable a locale à f() varvar a = a = 1212 ; ; windowwindow.alert.alert(("Dans f(), a est " "Dans f(), a est " + + typeoftypeof a a)) ; ; // Fonction g() définie dans la fonction f()// Fonction g() définie dans la fonction f() functionfunction g g()() {{ a++ ; a++ ; // Incrémentation de a définie dans fonction f() // Incrémentation de a définie dans fonction f() windowwindow.alert.alert(("Dans g(), a est ""Dans g(), a est " + + typeoftypeof a a)) ; ; }} windowwindow.alert.alert(("Avant g(), a vaut ""Avant g(), a vaut " + a + a)) ; ; gg()() ; ; windowwindow.alert.alert(("Après g(), a vaut ""Après g(), a vaut " + a + a)) ; ;}}windowwindow.alert.alert(("En global, a est ""En global, a est " + + typeoftypeof a a)) ; ;ff()() ; ;
202008:06:0808:06:08 Programmation Web 2013-2014Programmation Web 2013-2014
En global, a est undefinedEn global, a est undefinedDans f(), a est numberDans f(), a est numberAvant g(), a vaut 12Avant g(), a vaut 12Dans g(), a est numberDans g(), a est numberAprès g(), a vaut 13Après g(), a vaut 13
En global, a est undefinedEn global, a est undefinedDans f(), a est numberDans f(), a est numberAvant g(), a vaut 12Avant g(), a vaut 12Dans g(), a est numberDans g(), a est numberAprès g(), a vaut 13Après g(), a vaut 13
https://iut-info.univ-reims.fr/users/cutrona/exemplesS4/fermetures1.htmlhttps://iut-info.univ-reims.fr/users/cutrona/exemplesS4/fermetures1.html
Fermetures et événementsFermetures et événements
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><<htmlhtml>> <<headhead>> <<metameta http-equivhttp-equiv=="Content-Type""Content-Type" contentcontent=="text/html; "text/html;
charset=utf-8"charset=utf-8">> <<titletitle>>Fermetures et événementsFermetures et événements</</titletitle>> <<stylestyle typetype=='text/css''text/css'>> #id_bouton1#id_bouton1, , #id_bouton2#id_bouton2, , #id_bouton3#id_bouton3,, #id_bouton4#id_bouton4, , #id_bouton5#id_bouton5 {{ widthwidth : : 15em15em ; ; displaydisplay : : blockblock ; ; }} </</stylestyle>> <<scriptscript typetype=='text/javascript''text/javascript'>>/* Page suivante *//* Page suivante */</</scriptscript>> </</headhead>> <<bodybody>> <<inputinput idid=='id_bouton1''id_bouton1' typetype=='button''button' valuevalue=='Appuyez''Appuyez'>> <<inputinput idid=='id_bouton2''id_bouton2' typetype=='button''button' valuevalue=='Appuyez''Appuyez'>> <<inputinput idid=='id_bouton3''id_bouton3' typetype=='button''button' valuevalue=='Appuyez''Appuyez'>> <<inputinput idid=='id_bouton4''id_bouton4' typetype=='button''button' valuevalue=='Appuyez''Appuyez'>> <<inputinput idid=='id_bouton5''id_bouton5' typetype=='button''button' valuevalue=='Appuyez''Appuyez'>> </</bodybody>></</htmlhtml>>
212108:06:0808:06:08 Programmation Web 2013-2014Programmation Web 2013-2014
Fermetures et événementsFermetures et événements
windowwindow.onload = .onload = functionfunction ()() {{ varvar secondes = secondes = 55 ; ; forfor ((varvar i= i=11; i<; i<66; i++; i++)) {{ varvar bouton = bouton = documentdocument.getElementById.getElementById(('id_bouton''id_bouton' + i + i)) ; ; bouton.onclick = bouton.onclick = functionfunction()() {{ // Texte du bouton// Texte du bouton bouton.value = bouton.value = "Patientez ""Patientez " + secondes + + secondes + " secondes"" secondes" ; ; // Désactivation du bouton// Désactivation du bouton bouton.disabled = bouton.disabled = truetrue ; ; // Mise en place d'un compte à rebours// Mise en place d'un compte à rebours windowwindow.setTimeout.setTimeout(( // Fonction à lancer à la fin du compte à rebours// Fonction à lancer à la fin du compte à rebours functionfunction ()() {{ // Texte du bouton// Texte du bouton bouton.value = bouton.value = "Merci de votre attente""Merci de votre attente" ; ; // Activation du bouton// Activation du bouton bouton.disabled = bouton.disabled = falsefalse ; ; }}, secondes * , secondes * 10001000 /* Attente de millisecondes *//* Attente de millisecondes */)) ; ; }} }}}}
222208:06:0908:06:09 Programmation Web 2013-2014Programmation Web 2013-2014
https://iut-info.univ-reims.fr/users/cutrona/exemplesS4/https://iut-info.univ-reims.fr/users/cutrona/exemplesS4/fermetures7.htmlfermetures7.html
https://iut-info.univ-reims.fr/users/cutrona/exemplesS4/https://iut-info.univ-reims.fr/users/cutrona/exemplesS4/fermetures7.htmlfermetures7.html
Toutes les actions concernent Toutes les actions concernent le dernier bouton…le dernier bouton…Toutes les actions concernent Toutes les actions concernent le dernier bouton…le dernier bouton…
Fermetures et événementsFermetures et événements
windowwindow.onload = .onload = functionfunction ()() {{ varvar secondes = secondes = 55 ; ; forfor ((varvar i= i=11; i<; i<66; i++; i++)) {{ varvar bouton = bouton = documentdocument.getElementById.getElementById(('id_bouton''id_bouton' + i + i)) ; ; bouton.onclick = bouton.onclick = functionfunction()() {{ // Copie de bouton ?// Copie de bouton ? varvar btn = bouton ; btn = bouton ; // Texte du bouton// Texte du bouton btn.value = btn.value = "Patientez ""Patientez " + secondes + + secondes + " secondes"" secondes" ; ; // Désactivation du bouton// Désactivation du bouton btn.disabled = btn.disabled = truetrue ; ; // Mise en place d'un compte à rebours// Mise en place d'un compte à rebours windowwindow.setTimeout.setTimeout(( // // Fonction à lancer à la fin du compte à reboursFonction à lancer à la fin du compte à rebours functionfunction ()() {{ // Texte du bouton// Texte du bouton btn.value = btn.value = "Merci de votre attente""Merci de votre attente" ; ; // Activation du bouton// Activation du bouton btn.disabled = btn.disabled = falsefalse ; ; }}, secondes * , secondes * 10001000 /* Attente de millisecondes *//* Attente de millisecondes */)) ; ; }} }}}}
232308:06:0908:06:09 Programmation Web 2013-2014Programmation Web 2013-2014
https://iut-info.univ-reims.fr/users/cutrona/exemplesS4/https://iut-info.univ-reims.fr/users/cutrona/exemplesS4/fermetures9.htmlfermetures9.html
https://iut-info.univ-reims.fr/users/cutrona/exemplesS4/https://iut-info.univ-reims.fr/users/cutrona/exemplesS4/fermetures9.htmlfermetures9.html
Toutes les actions concernent Toutes les actions concernent le dernier bouton…le dernier bouton…Toutes les actions concernent Toutes les actions concernent le dernier bouton…le dernier bouton…
La capture des variables se fait à la fin de l’appel de la fonction contenant les déclarationsLa capture des variables se fait à la fin de l’appel de la fonction contenant les déclarations
Fermetures et événementsFermetures et événements
windowwindow.onload = .onload = functionfunction ()() {{ functionfunction patienter patienter((btnbtn)) {{ bouton.onclick = bouton.onclick = functionfunction()() {{ varvar secondes = secondes = 55 ; ; // Texte du bouton// Texte du bouton btn.value = btn.value = "Patientez ""Patientez " + secondes + + secondes + " secondes"" secondes" ; ; // Désactivation du bouton// Désactivation du bouton btn.disabled = btn.disabled = truetrue ; ; // Mise en place d'un compte à rebours// Mise en place d'un compte à rebours windowwindow.setTimeout.setTimeout(( // Fonction à lancer à la fin du compte à rebours// Fonction à lancer à la fin du compte à rebours functionfunction ()() {{ // Texte du bouton// Texte du bouton btn.value = btn.value = "Merci de votre attente""Merci de votre attente" ; ; // Activation du bouton// Activation du bouton btn.disabled = btn.disabled = falsefalse ; ; }}, secondes * , secondes * 10001000 /* Attente en millisecondes *//* Attente en millisecondes */)) ; ; }}}} forfor ((varvar i = i = 11; i<; i<66; i++; i++)) {{ varvar bouton = bouton = documentdocument.getElementById.getElementById(('id_bouton''id_bouton' + i + i)) ; ; patienter patienter((boutonbouton)) ; ; }}}}
242408:06:0908:06:09 Programmation Web 2013-2014Programmation Web 2013-2014
https://iut-info.univ-reims.fr/users/cutrona/exemplesS4/https://iut-info.univ-reims.fr/users/cutrona/exemplesS4/fermetures6.htmlfermetures6.html
https://iut-info.univ-reims.fr/users/cutrona/exemplesS4/https://iut-info.univ-reims.fr/users/cutrona/exemplesS4/fermetures6.htmlfermetures6.html
Les actions correspondent Les actions correspondent bien à chaque bouton !bien à chaque bouton !Les actions correspondent Les actions correspondent bien à chaque bouton !bien à chaque bouton !
Fermetures et événementsFermetures et événements
windowwindow.onload = .onload = functionfunction ()() {{ varvar secondes = secondes = 55 ; ; forfor ((varvar i= i=11; i<; i<66; i++; i++)) {{ varvar bouton = bouton = documentdocument.getElementById.getElementById(('id_bouton''id_bouton' + i + i)) ; ; ((functionfunction ((btnbtn)) {{ // Fonction anonyme appelée immédiatement// Fonction anonyme appelée immédiatement btn.onclick = btn.onclick = functionfunction()() {{ // Texte du bouton// Texte du bouton btn.value = btn.value = "Patientez ""Patientez " + secondes + + secondes + " secondes"" secondes" ; ; // Désactivation du bouton// Désactivation du bouton btn.disabled = btn.disabled = truetrue ; ; // Mise en place d'un compte à rebours// Mise en place d'un compte à rebours windowwindow.setTimeout.setTimeout(( // Fonction à lancer à la fin du compte à rebours// Fonction à lancer à la fin du compte à rebours functionfunction ()() {{ // Texte du bouton// Texte du bouton btn.value = btn.value = "Merci de votre attente""Merci de votre attente" ; ; // Activation du bouton// Activation du bouton btn.disabled = btn.disabled = falsefalse ; ; }}, secondes * , secondes * 10001000 /* Attente de millisecondes *//* Attente de millisecondes */)) ; ; }} }})()(boutonbouton)) ; ; }}}}
252508:06:0908:06:09 Programmation Web 2013-2014Programmation Web 2013-2014
https://iut-info.univ-reims.fr/users/cutrona/exemplesS4/https://iut-info.univ-reims.fr/users/cutrona/exemplesS4/fermetures10.htmlfermetures10.html
https://iut-info.univ-reims.fr/users/cutrona/exemplesS4/https://iut-info.univ-reims.fr/users/cutrona/exemplesS4/fermetures10.htmlfermetures10.html
Les actions correspondent Les actions correspondent bien à chaque bouton !bien à chaque bouton !Les actions correspondent Les actions correspondent bien à chaque bouton !bien à chaque bouton !
Fermetures et événementsFermetures et événements
windowwindow.onload = .onload = functionfunction ()() {{ varvar secondes = secondes = 55 ; ; forfor ((varvar i= i=11; i<; i<66; i++; i++)) {{ varvar bouton = bouton = documentdocument.getElementById.getElementById(('id_bouton''id_bouton' + i + i)) ; ; bouton.onclick = bouton.onclick = functionfunction()() {{ // Texte du bouton// Texte du bouton thisthis.value = .value = "Patientez ""Patientez " + secondes + + secondes + " secondes"" secondes" ; ; // Désactivation du bouton// Désactivation du bouton thisthis.disabled = .disabled = truetrue ; ; // Copie de this// Copie de this varvar that = that = thisthis ; ; // Mise en place d'un compte à rebours// Mise en place d'un compte à rebours windowwindow.setTimeout.setTimeout(( // Fonction à lancer à la fin du compte à rebours// Fonction à lancer à la fin du compte à rebours functionfunction ()() {{ // Texte du bouton// Texte du bouton that.value = that.value = "Merci de votre attente""Merci de votre attente" ; ; // Activation du bouton// Activation du bouton that.disabled = that.disabled = falsefalse ; ; }}, secondes * , secondes * 10001000 /* Attente de millisecondes *//* Attente de millisecondes */)) ; ; }} }}}}
262608:06:0908:06:09 Programmation Web 2013-2014Programmation Web 2013-2014
https://iut-info.univ-reims.fr/users/cutrona/exemplesS4/https://iut-info.univ-reims.fr/users/cutrona/exemplesS4/fermetures8.htmlfermetures8.html
https://iut-info.univ-reims.fr/users/cutrona/exemplesS4/https://iut-info.univ-reims.fr/users/cutrona/exemplesS4/fermetures8.htmlfermetures8.html
Les actions correspondent Les actions correspondent bien à chaque bouton !bien à chaque bouton !Les actions correspondent Les actions correspondent bien à chaque bouton !bien à chaque bouton !
JSON (JSON (JJavaavaSScript cript OObject bject NNotation) otation)
Format de Format de structure de donnéesstructure de données Utilise la Utilise la syntaxesyntaxe des des objets JavaScriptobjets JavaScript{"menu":{"menu":
{"id": "file", {"id": "file", "value": "File" "value": "File" "popup": {"item": [ {"value": "New" }, "popup": {"item": [ {"value": "New" }, {"value": "Open"}, {"value": "Open"}, {"value": "Close"}] }}} {"value": "Close"}] }}}
<menu id="file" value="File"><menu id="file" value="File"> <popup> <item value="New" /> <popup> <item value="New" /> <item value="Open" /> <item value="Open" /> <item value="Close" /> <item value="Close" /> </popup> </popup></menu></menu>
272708:06:0908:06:09 Programmation Web 2013-2014Programmation Web 2013-2014
Équivalent XMLÉquivalent XML
JSON (JSON (JJavaavaSScript cript OObject bject NNotation)otation)
Deux structures Deux structures :: ObjetObjet
{}{} {chaîne : valeur}{chaîne : valeur} {chaîne : valeur, chaîne : valeur, …}{chaîne : valeur, chaîne : valeur, …}
TableauTableau [][] [valeur][valeur] [valeur, valeur, …][valeur, valeur, …]
Valeur :Valeur : chaîne|nombre|objet|tableau|true|false|nullchaîne|nombre|objet|tableau|true|false|null
282808:06:0908:06:09 Programmation Web 2013-2014Programmation Web 2013-2014
http://www.json.org/http://www.json.org/
JSON (JSON (JJavaavaSScript cript OObject bject NNotation)otation)
292908:06:0908:06:09 Programmation Web 2013-2014Programmation Web 2013-2014
objectobject {}{}{ { membersmembers } }
membersmembers pairpairpairpair , , membersmembers
pairpair stringstring : : valuevalue
arrayarray [][][ [ elementselements ] ]
elementselements valuevaluevaluevalue , , elementselements
valuevalue stringstringnumbernumberobjectobjectarrayarraytruetruefalsefalsenull null
stringstring """"" " charschars " "
charschars charcharchar charschar chars
charchar any-Unicode-character-any-Unicode-character- except-except-""-or--or-\\-or--or- control-charactercontrol-character\"\"\\\\\/\/\b\b\f\f\n\n\r\r\t\t\u \u four-hex-digitsfour-hex-digits
http://www.json.org/http://www.json.org/
JSON (JSON (JJavaavaSScript cript OObject bject NNotation)otation)
303008:06:0908:06:09 Programmation Web 2013-2014Programmation Web 2013-2014
numbernumber intintint fracint fracint expint expint frac expint frac exp
intint digitdigitdigit1-9 digitsdigit1-9 digits- - digitdigit- - digit1-9 digitsdigit1-9 digits
fracfrac. . digitsdigits
expexp ee digitsdigits
digitsdigits digitdigitdigitdigit digitsdigits
ee eee+e+e-e-EEE+E+E- E-
http://www.json.org/http://www.json.org/
JSON (JSON (JJavaavaSScript cript OObject bject NNotation)otation)
313108:06:0908:06:09 Programmation Web 2013-2014Programmation Web 2013-2014
http://www.json.org/http://www.json.org/
JSON (JSON (JJavaavaSScript cript OObject bject NNotation)otation)
323208:06:0908:06:09 Programmation Web 2013-2014Programmation Web 2013-2014
http://www.json.org/http://www.json.org/
JSON (JSON (JJavaavaSScript cript OObject bject NNotation)otation)
333308:06:0908:06:09 Programmation Web 2013-2014Programmation Web 2013-2014
http://www.json.org/http://www.json.org/
JSON (JSON (JJavaavaSScript cript OObject bject NNotation)otation)
343408:06:0908:06:09 Programmation Web 2013-2014Programmation Web 2013-2014
http://www.json.org/http://www.json.org/
Développement orienté objetDéveloppement orienté objet
JavaScript est un langage JavaScript est un langage orienté objet à base orienté objet à base d’instancesd’instances et non à base de classes (POO et non à base de classes (POO orientée prototype)orientée prototype)
Une instance peut être construite à partir d’une Une instance peut être construite à partir d’une fonction constructeurfonction constructeur
thisthis est initialisé par le constructeur pour faire est initialisé par le constructeur pour faire référence à l’instance couranteréférence à l’instance courante
L’L’héritagehéritage dans la programmation objet orientée dans la programmation objet orientée prototype se fait prototype se fait à base de clonageà base de clonage
L’instance est composée de L’instance est composée de slotsslots de données de données (les fonctions sont des données !)(les fonctions sont des données !)
353508:06:0908:06:09 Programmation Web 2013-2014Programmation Web 2013-2014
Développement orienté objet : « attributs »Développement orienté objet : « attributs »
<<scriptscript typetype=='text/javascript''text/javascript'>>
functionfunction Animal Animal((nb_pattesnb_pattes)) {{
thisthis.pattes = nb_pattes ;.pattes = nb_pattes ;
}} ; ;
varvar garfield = garfield = newnew Animal Animal(4)(4) ; ;
varvar odie = odie = newnew Animal Animal(4)(4) ; ;
windowwindow.alert.alert(("Garfield a ""Garfield a "
+ garfield.pattes + + garfield.pattes + " pattes"" pattes")) ; ;
windowwindow.alert.alert(("Odie a " "Odie a "
+ odie+ odie[['pattes''pattes']] + + " pattes"" pattes")) ; ;
</</scriptscript>>
363608:06:0908:06:09 Programmation Web 2013-2014Programmation Web 2013-2014
Garfield a 4 pattes Garfield a 4 pattes Garfield a 4 pattes Garfield a 4 pattes
Odie a 4 pattes Odie a 4 pattes Odie a 4 pattes Odie a 4 pattes
prototypeprototype
Développement orienté objet : « attributs »Développement orienté objet : « attributs »
<<scriptscript typetype=='text/javascript''text/javascript'>>
functionfunction Animal Animal((nb_pattesnb_pattes)) {{
thisthis.pattes = nb_pattes ; .pattes = nb_pattes ; }} ; ;
varvar garfield = garfield = newnew Animal Animal(4)(4) ; ;
garfield.aime = garfield.aime = 'les lasagnes''les lasagnes' ; ;
varvar odie = odie = newnew Animal Animal(4)(4) ; ;
odie.aime = odie.aime = 'les os''les os' ; ;
windowwindow.alert.alert(("Garfield a ""Garfield a " + garfield.pattes + garfield.pattes
+ + " pattes et aime "" pattes et aime "+ garfield.aime+ garfield.aime)) ; ;
windowwindow.alert.alert(("Odie a ""Odie a " + odie.pattes + odie.pattes
+ + " pattes et aime "" pattes et aime "+ odie.aime+ odie.aime)) ; ;
</</scriptscript>>
373708:06:0908:06:09 Programmation Web 2013-2014Programmation Web 2013-2014
Garfield a 4 pattes et aime les lasagnesGarfield a 4 pattes et aime les lasagnesGarfield a 4 pattes et aime les lasagnesGarfield a 4 pattes et aime les lasagnes
Odie a 4 pattes et aime les osOdie a 4 pattes et aime les osOdie a 4 pattes et aime les osOdie a 4 pattes et aime les os
Développement orienté objet : « méthodes »Développement orienté objet : « méthodes »
<<scriptscript typetype=='text/javascript''text/javascript'>>functionfunction Animal Animal((nb_pattesnb_pattes)) {{ thisthis.pattes = nb_pattes ;.pattes = nb_pattes ; thisthis.dormir = .dormir = functionfunction()() { { returnreturn "ZZZzzz...""ZZZzzz..." ; ; }}}} ; ;Chat.prototype = Chat.prototype = newnew Animal Animal(4)(4) ; ;functionfunction Chat Chat()() { }{ } ; ;Chien.prototype = Chien.prototype = newnew Animal Animal(4)(4) ; ;functionfunction Chien Chien()() { }{ } ; ;
varvar garfield = garfield = newnew Chat Chat()() ; ;varvar odie = odie = newnew Chien Chien()() ; ;
windowwindow.alert.alert(("Garfield a ""Garfield a " + garfield.pattes + garfield.pattes)) ; ;
windowwindow.alert.alert(("Garfield, au lit ! " "Garfield, au lit ! " + garfield.dormir+ garfield.dormir())()) ; ;
windowwindow.alert.alert(("Odie a ""Odie a " + odie.pattes + odie.pattes)) ; ;
383808:06:0908:06:09 Programmation Web 2013-2014Programmation Web 2013-2014
Garfield a 4 pattes Garfield a 4 pattes Garfield a 4 pattes Garfield a 4 pattes
ZZZzzz...ZZZzzz...ZZZzzz...ZZZzzz...
Odie a 4 pattes Odie a 4 pattes Odie a 4 pattes Odie a 4 pattes
Développement orienté objet : « méthodes »Développement orienté objet : « méthodes »
<<scriptscript typetype=='text/javascript''text/javascript'>>functionfunction Animal Animal((nb_pattesnb_pattes)) {{ thisthis.pattes = nb_pattes ;.pattes = nb_pattes ; thisthis.dormir = .dormir = functionfunction()() {{ returnreturn "ZZZzzz...""ZZZzzz..." ; ; }}}} ; ;Chat.prototype = Chat.prototype = newnew Animal Animal(4)(4) ; ;functionfunction Chat Chat()() {{ }} ; ;Chien.prototype = Chien.prototype = newnew Animal Animal(4)(4) ; ;functionfunction Chien Chien()() {{ thisthis.dormir = .dormir = functionfunction()() {{ returnreturn "...""..." ; ; }}}} ; ;varvar garfield = garfield = newnew Chat Chat()() ; ;varvar odie = odie = newnew Chien Chien()() ; ;windowwindow.alert.alert(("Garfield, au lit ! " "Garfield, au lit ! " + garfield.dormir+ garfield.dormir())()) ; ;
windowwindow.alert.alert(("Odie, au lit ! " "Odie, au lit ! " + odie.dormir+ odie.dormir())()) ; ;</</scriptscript>>
393908:06:0908:06:09 Programmation Web 2013-2014Programmation Web 2013-2014
ZZZzzz...ZZZzzz...ZZZzzz...ZZZzzz...
............
Objets anonymesObjets anonymes
<<scriptscript typetype=='text/javascript''text/javascript'>>functionfunction Animal Animal((paramparam)) {{ thisthis.pattes = param.pattes || .pattes = param.pattes || 44 ; ; thisthis.aime = param.aime || .aime = param.aime || '?''?' ; ;}} ; ;Chat.prototype = Chat.prototype = newnew Animal Animal(({{pattes : pattes : 44,, aime : aime : 'le poisson''le poisson' }})) ; ;functionfunction Chat Chat()() {{ }} ; ;Chien.prototype = Chien.prototype = newnew Animal Animal(({{pattes : pattes : 44,, aime : aime : 'la viande''la viande' }})) ; ;functionfunction Chien Chien()() { }{ } ; ;varvar garfield = garfield = newnew Chat Chat()() ; ;varvar odie = odie = newnew Chien Chien()() ; ;
windowwindow.alert.alert(("Garfield a ""Garfield a " + garfield.pattes + + garfield.pattes + " pattes"" pattes")) ; ;windowwindow.alert.alert(("Garfield aime ""Garfield aime " + garfield.aime + garfield.aime)) ; ;windowwindow.alert.alert(("Odie a ""Odie a " + odie.pattes + + odie.pattes + " pattes"" pattes")) ; ;windowwindow.alert.alert(("Odie aime ""Odie aime " + odie.aime + odie.aime)) ; ;</</scriptscript>>
404008:06:0908:06:09 Programmation Web 2013-2014Programmation Web 2013-2014
Garfield a 4 pattes Garfield a 4 pattes Garfield a 4 pattes Garfield a 4 pattes
Garfield aime le poissonGarfield aime le poissonGarfield aime le poissonGarfield aime le poisson
Odie a 4 pattes Odie a 4 pattes Odie a 4 pattes Odie a 4 pattes
Odie aime la viandeOdie aime la viandeOdie aime la viandeOdie aime la viande
Outils de développement Web du navigateurOutils de développement Web du navigateur
Accessibles dans tous les navigateurs récentsAccessibles dans tous les navigateurs récents Permet :Permet :
l’éditionl’édition le débogagele débogage le suivile suivi
de tous les éléments constitutifs d’une page Web :de tous les éléments constitutifs d’une page Web : HTMLHTML CSSCSS JavaScriptJavaScript échanges HTTP, AJAXéchanges HTTP, AJAX
Traces JavaScript avec Traces JavaScript avec console.log(console.log(msgmsg))414108:06:0908:06:09 Programmation Web 2013-2014Programmation Web 2013-2014
Outils de développement Web du navigateurOutils de développement Web du navigateur
424208:06:1008:06:10 Programmation Web 2013-2014Programmation Web 2013-2014
Outils de développement Web du navigateurOutils de développement Web du navigateur
434308:06:1008:06:10 Programmation Web 2013-2014Programmation Web 2013-2014
Outils de développement Web du navigateurOutils de développement Web du navigateur
444408:06:1008:06:10 Programmation Web 2013-2014Programmation Web 2013-2014