Download presentation
Presentation is loading. Please wait.
1
Web DevelopmEnt Java Script
קרן כליף
2
מהי Java-script? השפה לקטעי תכנות בדפי HTML וב- WEB בכלל, נכתוב בה את התנהגות הדף (נגיב לאירועים) למרות שמה, אין קשר לשפת JAVA
3
פלטים שונים <!DOCTYPE> <html> <body> <p id="msg1">message 1</p> <p id="msg2">message 2</p> <p id="msg3">message 3</p> <script> document.getElementById("msg1").innerHTML = "Hi from document.getElementById"; document.write("Hi from document.write"); window.alert("Hi from window.alert"); console.log("Hi from console.log"); </script> </body> </html> document.write כותב בסוף הדף בעוד ש document.getElementById כותב במקום ייעודי
4
עדכון HTML באמצעות Java-script
עדכון HTML באמצעות Java-script <head> <script src="02_myFirstScript.js"></script> <script> function updateMessage2() { document.getElementById("greetingMsg2").style.fontSize = "15px"; document.getElementById("greetingMsg2").style.fontWeight = "bold"; document.getElementById("greetingMsg2").innerHTML = "After Click Me 2"; } </script> </head> <body> <button type="button" onclick= 'document.getElementById("greetingMsg1").innerHTML = "After Click Me 1"'> Click Me 1!</button> <button type="button" onclick="updateMessage2()">Click Me 2!</button> <button type="button" onclick="updateMessage3()">Click Me 3!</button> <p id="greetingMsg1"></p> <p id="greetingMsg2"></p> <p id="greetingMsg3"></p> </body>
5
עדכון HTML באמצעות Java-script
עדכון HTML באמצעות Java-script 02_myFirstScript.js function updateMessage3() { document.getElementById("greetingMsg3").style.fontSize = "25px"; document.getElementById("greetingMsg3").style.color = "blue"; document.getElementById("greetingMsg3").innerHTML = "After Click Me 3"; }
6
<!DOCTYPE> <html> <head> <script> function calcBMI(weight, height) { return weight/Math.pow(height, 2); } function displayBMI() { var weight = document.getElementById("weight").value; var height = document.getElementById("height").value; document.getElementById("result").innerHTML = "BMI is " + calcBMI(weight, height); </script> </head> <body> Weight: <input type="text" id="weight"/> Height: <input type="text" id="height"/> <button type="button" onclick="displayBMI()">Calc your BMI!</button> <p id="result"></p> </body> </html> פונקציות
7
פרמטרים הנשלחים לפונקציה
פרמטרים הנשלחים לפונקציה <body> <script> function calcBMI(weight, height) { return weight/Math.pow(height, 2); } function calcBMI2(weight, height) { if (height == undefined) return -1; document.write(calcBMI(80, 1.87) + "<br/>"); document.write(calcBMI(80) + "<br/>"); document.write(calcBMI2(80, 1.87) + "<br/>"); document.write(calcBMI2(80) + "<br/>"); </script> </body> ניתן לא לשלוח לפונקציה את אחד הפרמטרים, ואז התשובה כנראה תהיה NaN, אלא אם מטופלת בקוד
8
מספר משתנה של פרמטרים <!DOCTYPE> <html> <head> </head> <body> <script> function calcAverage() { var sum = 0; for (i=0 ; i < arguments.length ; i++) { sum += arguments[i]; } return sum/arguments.length; document.write(calcAverage(2,4,6) + "<br/>"); document.write(calcAverage(2,2,2,2,2,8) + "<br/>"); </script> </body> </html>
9
Closures – תחליף למשתנה סטטי
ב- JavaScript אין טיפוס כזה, אבל ניתן לממש צורך זה באמצעות פונקציה אנונימית פנימית פונקציה אנונימית – מבטיחה שאף אחד מבחוץ לא יוכל לשנות את ערך המשתנה פנימית – כי ב- JavaScript פונקציה פנימית יכולה לגעת במשתנים המוגדרים בפונקציה החיצונית
10
משתנה לוקאלי של הפונקציה
Closures - דוגמה <body> <p>The button was pressed <span id=counter>0</span> times</p><br/> <button onclick=incrementCounter()>Press Me</button> <script> var inc = (function() { var counter = 0; return function() {return ++counter;} })(); function incrementCounter() { document.getElementById("counter").innerHTML = inc(); } </script> </body> פונקציה אנונימית. נוצרת פעם אחת ברגע ההגדרה ולא ניתן ליצרה שוב כי אין לה שם משתנה לוקאלי של הפונקציה פונקציה פנימית (Nested Function) יכולה לגעת במשתנים של הפונקציה החיצונית
11
<!DOCTYPE> <html> <head> <script> function changeText() { document.getElementById("message").innerHTML = "This text is here while mouse hover"; document.getElementById("message").style.color = "red"; } function changeTextAgain() { "This is a message that changes when mouse hover"; document.getElementById("message").style.color = "black"; </script> </head> <body> <p id="message" onmouseover="changeText()" onmouseout="changeTextAgain()"> This is a message that changes when mouse hover<p> </body> </html> אירועים
12
שימוש ב- this this מתייחס ל- h1 <body> <h1 onmouseover="changeText(this)" onmouseout="restoreTextForH1(this)">Some header1</h1> <p onmouseover="changeText(this)" onmouseout="restoreTextForP(this)">Some paragraph</p> <script> function changeText(elem) { elem.innerHTML = "mouse is over me"; elem.style.color = "red"; } function restoreTextForH1(elem) { elem.innerHTML = "Some header1"; elem.style.color = "black"; function restoreTextForP(elem) { elem.innerHTML = "Some paragraph"; </script> </body> this מתייחס ל- p
13
טווח הכרה של משתנים <!DOCTYPE> <html> <body>
<script> var globalVar = 8; function foo() { var myVar1 = 1; myVar2 = 2; globalVar = 3; } document.write("<b>*** start writing</b><br/>"); /* document.write(myVar1 + "<br/>"); */ /* document.write(myVar2 + "<br/>"); */ document.write(globalVar + "<br/>"); foo(); document.write(myVar2 + "<br/>"); document.write(window.myVar1 + "<br/>"); document.write(window.myVar2 + "<br/>"); document.write("<b>*** end</b><br/>"); </script> </body> </html> טווח הכרה של משתנים משתנה גלובלי מוכר בכל מקום משתנה לוקאלי מוכר רק בפונקציה משתנה לוקאלי שמוגדר ללא טיפוס הופך לגלובלי השורות האפורות תוקעות את התוכנית כי פונות למשתנה שאינו מוכר ניסיון פניה למשתנה גלובלי שלא קיים
14
סוגי טיפוסים ישנם 5 סוגי טיפוסים: string number boolean Object
function ניתן ליצור אותם גם כטיפוסים בסיסיים וגם כאובייקטים. עדיף כטיפוס בסיסי! Object, Date, Array
15
<body> <script> var someText1 = "Hello World!"; document.write(someText1 + " len is " + someText1.length + "<br/>"); var someText2 = "Hello 'gogo'"; document.write(someText2 + "<br/>"); var someText3 = 'Hello "gogo"'; document.write(someText3 + "<br/>"); var someText4 = "Hello \"gogo\""; document.write(someText4 + "<br/>"); var someLongText = "This line is \ very long and is written over \ more than onle line"; document.write(someLongText + "<br/>"); </script> </body> מחרוזות
16
לא להגדיר טיפוסים בסיסיים כאובייקטים!
לא להגדיר טיפוסים בסיסיים כאובייקטים! ניתן להגדיר טיפוסים בסיסיים כאובייקטים (באמצעות הפקודה new) אך אין לכך כל ערך מוסף ואופן זה מאט את פעולת המערכת var x = new String(); // Declares x as a String object var y = new Number(); // Declares y as a Number object var z = new Boolean(); // Declares z as a Boolean object <body> <script> var x = 5; var y = new Number(5); var z = new Number(5); document.write("x == y ?" + (x == y) + "<br/>"); document.write("x === y ?" + (x === y) + "<br/>"); document.write("y == z ?" + (y == z) + "<br/>"); document.write("y === z ?" + (y === z) + "<br/>"); </script> </body> פעולת השוואה עם == עבור טיפוסים בסיסיים בודקת את התוכן, ועבור אובייקטים בודקת האם ההפניה זהה. בדיקת השווה עם === בודקת שגם הערך וגם הטיפוס זהים
17
אופן שליחת הפרמטרים פרמטרים מטיפוס בסיסי נשלחים by-value בעוד שפרמטרים מטיפוס אובייקטים נשלחים by-reference המשמעות: האם הפונקציה יכולה או לא יכולה לשנות את הפרמטר
18
אובייקטים בשפת JavaScript אין טיפוסים, כל המשתנים מטיפוס var
ניתן להגדיר אובייקטים המכילים תכונות (properties) ופעולות (methods), כאשר לכל תכונה יש שם וערך הגדרה של אובייקט אינה מצריכה יצירה של טיפוס, אלא רק הגדרת ערכים לאוסף תכונות
19
אובייקטים <body> <p id="student1Details"></p>
<p id="functionAccess"></p> <script> var student = { name: "gogo", id: 5566, average: 87.2, getDetails : function() { return "Name: " + this.name + " (id: " + this.id + "), Average: " + this.average; } }; document.getElementById("student1Details").innerHTML = student[name] + "'s id is " + student.id + ", and his average: " + student.average; document.getElementById("student2Details").innerHTML = student.getDetails(); document.getElementById("functionAccess").innerHTML = student.getDetails()+ "<br/>" + " VS." + "<br/>" + student.getDetails; </script> </body> אובייקטים בניגוד לשפות אחרות, השימוש ב- this הינו חובה, אחרת התכונה אינה מזוהה ניתן לגשת לתכונות האובייקט באמצעות נקודה או באמצעות []
20
מעבר על תכונות האובייקט עם לולאה
מעבר על תכונות האובייקט עם לולאה <body> <p id="studentDetails"></p> <script> var student = { name: "gogo", id: 5566, average: 87.2, getDetails : function() { return "Name: " + this.name + " (id: " + this.id + "), Average: " + this.average; } }; var res = "<h3>stduent properties and values:</h3>"; for(var attr in student){ res += attr + ': ' + student[attr] + "<br/>"; document.getElementById("studentDetails").innerHTML = res; </script> </body>
21
הפעלת מתודות באמצעות call
הפעלת מתודות באמצעות call <body> <script> var person = { name: "gogo", id: 5566, getDetails : function() { return "Name: " + this.name + " (id: " + this.id + ")"; } }; var student = { average: 87.2, document.write(person.getDetails.call(student)); </script> </body>
22
מטעמי יעילות, נמנע מלהגדיר מערכים באמצעות new
<!DOCTYPE> <html> <body> <script> var desserts = new Array("Cake", "Cookies", "Ice Cream"); var desserts = ["Cake", "Cookies", "Ice Cream"]; document.write(desserts[1] + "<br/>"); document.write(desserts + "<br/><br/>"); desserts.push("Sorbe"); desserts[desserts.length] = "Fruits"; var numOfDesserts = desserts.length; var txt = "There are " + desserts.length + " kinds of desserts:" + "<br/>"; txt += "<ul>"; for (i = 0; i < numOfDesserts; i++) { txt += "<li>" + desserts[i] + "</li>"; } txt += "</ul>"; document.write(txt + "<br/>"); </script> </body> </html> מערכים מטעמי יעילות, נמנע מלהגדיר מערכים באמצעות new
23
מיון מערך כברירת מחדל מיון הוא לקסיקוגרפי (גם אם הערכים הם מספריים), ולכן יש לספק לפונקצית המיון sort פרמטר שהוא פונקציה המממשת את אופן ההשוואה <body> <script> function showCakes(cakes) { var txt = ""; var numOfCakes = cakes.length; for (i=0 ; i < numOfCakes ; i++) { txt += cakes[i].name + "(" + cakes[i].calories + ") | "; } document.write(txt + "<br/><br/>");
24
מיון מערך var cake1 = { name: "chocolate", calories: 450 };
name: "apple pie", calories: 340 var cake3 = { name: "cheese", calories: 280 var cakes = [cake1, cake2, cake3]; document.write("The cakes: <br/>"); showCakes(cakes); document.write("The cakes sorted by name: <br/>"); cakes.sort(function(a, b){return a.name.localeCompare(b.name);}); document.write("The cakes sorted by calories: <br/>"); cakes.sort(function(a, b){return a.calories > b.calories;}); </script> מיון מערך
25
HTml dom DOM – DocumentObjectModel
באמצעות פניה לעץ זה ניתן לשנות את תוכן דף ה- HTML (הוספה, הסרה, עדכון) באמצעות קוד JavaScript DOM הוא גם סטנדרט שמוגדר ע"י W3C
26
מחזיר HTMLCollection – אינו מערך!
<body> <h3>This is a title</h3> <p id="msg">This is a message</p><br/> <button onclick="changeTextColor()">Color text</button> <button onclick="changeH3Color()">Color titles</button> <h3>This is another title</h3> <script> function changeTextColor() { document.getElementById("msg").style.color = "red"; } function changeH3Color() { var allH3 = document.getElementsByTagName('h3'); for (i=0 ; i < allH3.length ; i++) { allH3[i].style.color = "green"; </script> </body> דוגמאות מחזיר HTMLCollection – אינו מערך!
27
דוגמאות <body> <h3>This is a title</h3> <h3>This is another title</h3> <button onclick="addOnHoverEventH3()">Add On hover Event to H3</button><br/><br/> <script> function addOnHoverEventH3() { var allH3 = document.getElementsByTagName('h3'); for (i=0 ; i < allH3.length ; i++) { allH3[i].addEventListener("mouseover", function() {this.style.color = "pink"}); allH3[i].addEventListener("mouseout", function() {this.style.color = "black"}); } </script> </body>
28
דוגמאות <head> <style> .bigFont { font-size: 30px; } </style> </head> <body> <p id="toEnlarge">some text to enlarge</p> <button onclick="document.getElementById('toEnlarge').setAttribute ('class', 'bigFont'); ">Enlarge Font</button><br/><br/> <button onclick="addLine()">Add another paragraph</button><br/><br/> <script> function addLine() { var newParagraph = document.createElement("p"); var theTxt = document.createTextNode("This is the added text"); newParagraph.appendChild(theTxt); document.body.appendChild(newParagraph); </script> </body>
29
הוספת אירועים ע"י DOM בדוגמה הבאה ישנו אלמנט p בתוך אלמנט div, ששניהם מגיבים למעבר עם העכבר השאלה: איזה אירוע יופעל קודם: של האלמנט הפנימי או של החיצוני? Event Capturing – אירוע של אלמנט חיצוני ואז אירוע של אלמנט פנימי Event Bubbling – אירוע של אלמנט פנימי ואז אירוע של אלמנט חיצוני (ברירת מחדל) <body onload="addEventsByDay()"> <div> <p style="border:1px solid black; width: 200px;">Here is some text</p> </div> <p id="newTxt"></p> <script> … </script> </body>
30
ביום שלישי בשאר ימות השבוע
31
<script> function addEventsByDay() { var elemP = document.getElementsByTagName("p")[0]; var elemDiv = document.getElementsByTagName("div")[0]; if (new Date().getDay() == 2) { document.getElementById("newTxt").innerHTML = "using Event Capturing: outer then inner element<br/>"; elemP.addEventListener("mouseover", function(){ document.getElementById("newTxt").innerHTML += "over p | ";}, true); elemDiv.addEventListener("mouseover", function(){ document.getElementById("newTxt").innerHTML += "over div | ";}, true); } else { "using Event Bubbling: inner then outer element<br/>"; document.getElementById("newTxt").innerHTML += "over p | ";}); document.getElementById("newTxt").innerHTML += "over div | ";}); </script> עבור event capturing
32
מאחר ונרצה להסירה עם לחיצה על הכפתור, יש לתת לה שם
הסרת אירוע <body> <div> <p style="border:1px solid black; width: 200px;">Here is some text</p> </div> <button onclick="onButtonClick()">Stop print on over</button><br/><br/> <p id="newTxt"></p> <script> var elemP = document.getElementsByTagName("p")[0]; var elemDiv = document.getElementsByTagName("div")[0]; elemP.addEventListener("mouseover", onPMouseOver); elemDiv.addEventListener("mouseover", function() { document.getElementById("newTxt").innerHTML += "over div | ";}); function onPMouseOver() { document.getElementById("newTxt").innerHTML += "over p | "; } function onButtonClick() { document.getElementById("newTxt").innerHTML += "<br/><h3>After stopping events from p<h3<"; elemP.removeEventListener("mouseover",onPMouseOver); </script> </body> מאחר ונרצה להסירה עם לחיצה על הכפתור, יש לתת לה שם
33
html head style body h3 #text=This is a title button #text=color P div #text=kuku p=this is the first p #text=bla p=this is the second p #text hr p=“” html head style body h3 #text=This is a title button #text=Color P div #text=kuku p=this is the first p #text=bla p=this is the second p #text hr P=“” DOM Navigation מבנה HTML הינו מבנה היררכי שניתן לטייל עליו באמצעות פקודות DOM <body> <h3>This is a title</h3> <button onclick="colorEvenParagraphs()">Color P</button><br/> <div id="test">kuku <p>this is the first p</p>bla <p>this is the second p</p> </div> <hr/> <p id="result"></p> <script>…</script> </body>
34
function colorEvenParagraphs() {
<script> function colorEvenParagraphs() { var resElem = document.getElementById("result"); resElem.innerHTML = ""; resElem.innerHTML += "h3 nodeValue: " + document.getElementsByTagName("h3")[0].childNodes[0].nodeValue + "<br/>"; var divChildren = document.getElementsByTagName("div")[0].childNodes; resElem.innerHTML += "div num of childs: " + divChildren.length + "<br/>"; resElem.innerHTML += "<hr/>"; resElem.innerHTML += "div id=" + document.getElementsByTagName("div")[0].getAttribute("id") + " | div text: " + document.getElementById("test").innerHTML; resElem.innerHTML += "div child[0] name: " + divChildren[0].nodeName + ", value:" + divChildren[0].nodeValue + "<br/>"; ... } </script> html head style body h3 #text=This is a title button #text=color P div #text=kuku p=this is the first p #text=bla p=this is the second p #text hr p=“” <body> <h3>This is a title</h3> <button onclick="colorEvenParagraphs()">Color P</button><br/> <div id="test">kuku <p>this is the first p</p>bla <p>this is the second p</p> </div> <hr/> <p id="result"></p> <script>…/script> </body>
35
function colorEvenParagraphs() { ...
<script> function colorEvenParagraphs() { ... for (i=1 ; i < divChildren.length ; i++) { resElem.innerHTML += "child[" + i + "] name: " + divChildren[i].nodeName + " | parent name: " + divChildren[i].parentNode.nodeName + " | value: " + divChildren[i].innerHTML; if (divChildren[i].nodeType == 3) resElem.innerHTML += " | <span style=\"color: red;\">" + divChildren[i].nodeValue + "</span>"; else divChildren[i].style.color = "red"; resElem.innerHTML += "<br/>"; } </script> 3 עבור TEXT_NODE html head style body h3 #text=This is a title button #text=color P div #text=kuku p=this is the first p #text=bla p=this is the second p #text hr p=“” <body> <h3>This is a title</h3> <button onclick="colorEvenParagraphs()">Color P</button><br/> <div id="test">kuku <p>this is the first p</p>bla <p>this is the second p</p> </div> <hr/> <p id="result"></p> <script>…/script> </body>
36
BOM – Browser Object model
הרעיון – לאפשר ל- JavaScript "לדבר" עם הדפדפן הגישה הינה באמצעות המשתנה הנקרא window, שיכול לגשת לכל המשתנים והפונקציות הגלובליות, וגם כמובן למשתנה document (שמתייחס ל- HTML עצמו)
37
מיותר, כי המידע אינו משתנה בעקבות שינוי גודל הדפדפן
<body> <h4>Screen Data</h4> <p id="screenData"></p> <h4>Dimensions Data</h4> <p id="dimensionsData"></p> <script> showScreenData(); showDimensions(); window.addEventListener("resize", showScreenData); window.addEventListener("resize", showDimensions); function showScreenData() { ... } function showDimensions() { </script> </body> BOM | גישה לדפדפן ולמסך מיותר, כי המידע אינו משתנה בעקבות שינוי גודל הדפדפן
38
BOM | גישה לדפדפן ולמסך <script> function showScreenData() {
var screenDataTxt = document.getElementById("screenData"); screenDataTxt.innerHTML = "width = " + screen.width + "<br/>"; screenDataTxt.innerHTML += "height = " + screen.height + "<br/>"; screenDataTxt.innerHTML += "availWidth = " + screen.availWidth + "<br/>"; screenDataTxt.innerHTML += "availHeight = " + screen.availHeight + "<br/>"; screenDataTxt.innerHTML += "colorDepth = " + screen.colorDepth + "<br/>"; screenDataTxt.innerHTML += "pixelDepth = " + screen.pixelDepth + "<br/>"; } function showDimensions() { var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; var h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight; document.getElementById("dimensionsData").innerHTML = "window width: " + w + ", window height: " + h; </script> לתמיכה בדפדפנים שונים
39
BOM | מידע על ה- URL <body> <p id="locationData"></p> <button onclick="openYnet()">Open YNET</button> <script> var pElem = document.getElementById("locationData"); pElem.innerHTML = "Location: " + window.location.href + "<br/>"; pElem.innerHTML += "Hostname: " + window.location.hostname + "<br/>"; pElem.innerHTML += "Path: " + window.location.pathname + "<br/>"; pElem.innerHTML += "Protocol: " + window.location.protocol + "<br/>"; function openYnet() { window.open(' '_blank'); } </script> </body>
40
BOM | גישה לדף הבא והקודם בדפדפן
BOM | גישה לדף הבא והקודם בדפדפן <body> <button onclick="previousPage()">Back to last page</button>    <button onclick="nextPage()">Next page</button> <script> function nextPage() { window.history.forward(); } function previousPage() { window.history.back(); </script> </body> מטעמי אבטחה, לא מתאפשר לקבל את רשימת ההיסטוריה, אלא רק לנווט בין הדפים האחרונים
41
BOM | Pop-ups <body> <p id="msg"></p> <script> window.alert("This is an alert"); var name = window.prompt("Enter your name: "); var res = window.confirm("Are you sure your name is " + name + "?"); if (res == true) document.getElementById("msg").innerHTML = "Hi " + name; else document.getElementById("msg").innerHTML = "Don't you know your name??"; </script> </body>
42
BOM | TIMER <body onload="changeBackgroundColor()">
<p style="border: 1px solid black; padding: 5px;">bla bla bla</p> <script> var incCounter = (function () { var counter = 0; return function () { return counter += 1; } })(); function changeBackgroundColor() { var theParagraph = document.getElementsByTagName('p'); var theInterval = setInterval(changeColor, 1000); function changeColor() { document.getElementsByTagName('p')[0].style.backgroundColor = getRandomColor(); if (incCounter() == 3) clearInterval(theInterval); } function getRandomColor() {…} </script> </body> BOM | TIMER לצד setInterval יש גם את setTimeout שתרוץ פעם אחת בלבד. את setTimout ניתן לבטל, בתנאי שעוד לא רצה, באמצעות clearTimout.
43
BOM - TIMER ... <script> … function getRandomColor() {
var letters = ' ABCDEF'; var color = '#'; for (var i = 0; i < 6; i++) { color += letters[Math.floor(Math.random() * 16)]; } return color; </script>
44
BOM | Cookies cookies הם ערכים שניתן לשמור במחשב עם מידע לשימוש חוזר, לרוב שם המשתמש וסיסמה, העדפות וכד' העוגייה נוצרת בשרת, ששולחת אותה דרך הדפדפן לשמירה בזיכרון המחשב Cookie הינו זוג של key-value טקסטואליים
45
במידה ונכנסו לדף שוב בטווח של 30 שניות מהפעם הראשונה
BOM | COOKIES במידה ונכנסו לדף שוב בטווח של 30 שניות מהפעם הראשונה
46
BOM | COOKIES <body onload="setHelloMessage()"> <form method="get" id="inputForm" style="display: none;"> <fieldset> <legend>Enter your details:</legend> First Name: <input type="text" id="firstName" /><br/><br/> Last Name: <input type="text" id="lastName" /><br/><br/> <button onclick="saveDetails()" type="button">Save Details</button> </fieldset> </form> <p id="msg"></p> <hr/> <p id="logMsg" style="color: green;">Log Msg here<br/></p> <script> ... </script> </body> הטופס אינו מוצג בהתחלה ברירת המחדל הינה הערך submit ואז הדף נטען מחדש, ולכן מציג את הטופס מחדש. כך הדף אינו נטען מחדש
47
<script> function setCookie(cookieName, cookieValue, secondsToExpire) {...} function getCookie(cookieName) {...} function setHelloMessage() { var firstName = getCookie("firstName"); document.getElementById("logMsg").innerHTML += "getting cookie firstName=" + firstName + "<br/>"; var lastName = getCookie("lastName"); "getting cookie lastName=" + lastName + "<br/>"; document.getElementById("logMsg").innerHTML += "<hr/>"; if (firstName == "" && lastName == "") { document.getElementById("inputForm").style.display = 'block'; } else { document.getElementById("msg").innerHTML = "Hello " + firstName + " " + lastName; function saveDetails() {...} </script>
48
<script> function setCookie(cookieName, cookieValue, secondsToExpire) {...} function getCookie(cookieName) { var currentCookies = decodeURIComponent(document.cookie); document.getElementById("logMsg").innerHTML += "currentCookies: " + currentCookies + "<br/>"; var name = cookieName + "="; var allCookies = currentCookies.split(';'); for (var i = 0; i < allCookies.length; i++) { allCookies[i] = allCookies[i].trim(); if (allCookies[i].indexOf(name) == 0) { return allCookies[i].substring(name.length, allCookies[i].length); } return ""; function setHelloMessage() {...} function saveDetails() {...} </script>
49
<script> function setCookie(cookieName, cookieValue, secondsToExpire) {...} function getCookie(cookieName) {...} function setHelloMessage() { ... } function saveDetails() { var firstName = document.getElementById("firstName").value; var lastName = document.getElementById("lastName").value; if (firstName != "" && firstName != null) { setCookie("firstName", firstName, 30); if (lastName != "" && lastName != null) { setCookie("lastName", lastName, 60); document.getElementById("msg").innerHTML = "Hello New Friend <b>" + firstName + " " + lastName + "</b>"; } </script>
50
<script> function setCookie(cookieName, cookieValue, secondsToExpire) { var d = new Date(); d.setTime(d.getTime() + (secondsToExpire * 1000)); var expires = "expires=" + d.toGMTString(); document.cookie = cookieName + "=" + cookieValue + " ; " + expires + ";path=/"; document.getElementById("logMsg").innerHTML += "setting document.cookie: " + cookieName + "=" + cookieValue + ";" + expires + ";path=/<br/>"; } function getCookie(cookieName) {...} function setHelloMessage() {...} function saveDetails() {...} </script>
51
AJAX AJAX - Asynchronous JavaScript And XML
המידע החיצוני חייב להיות באותו שרת ניתן לעדכן רק חלק מהדף ולא לטעון את כולו!
52
התוספת לשם הקובץ דואגת שהוא יטען מחדש ולא ילקח מה- cache
AJAX - דוגמה <body> <h2>The XMLHttpRequest Object</h2> <button type="button" onclick="loadDoc( '25_some_text.txt?t=' + Math.random(), updateSomeTextPara1)">Request data 1!</button>     '25_some_text.txt', updateSomeTextPara2)">Request data 2!</button> <h3>Some text 1</h3> <p id="someText1"></p> <h3>Some text 2</h3> <p id="someText2"></p> <p id="currentTime" style="color: blue;"></p> <p id="msg" style="color: green;"></p> <script> ... </script> </body> התוספת לשם הקובץ דואגת שהוא יטען מחדש ולא ילקח מה- cache
53
ונשים לב שחלק זה של הדף לא השתנה (התאריך זהה), משמע לא כל הדף נטען מחדש אלא עודכן באופן נקודתי
54
AJAX - הסקריפט <script>
document.getElementById("currentTime").innerHTML = new Date(); function loadDoc(theUrl, theFunc) { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) { theFunc(this); } }; xhttp.open("GET", theUrl, true); xhttp.send(); document.getElementById("msg").innerHTML = "updated page with data from " + theUrl; function updateSomeTextPara1(xhttp) { document.getElementById("someText1").innerHTML = xhttp.responseText; function updateSomeTextPara2(xhttp) { document.getElementById("someText2").innerHTML = xhttp.responseText; </script> AJAX - הסקריפט
55
<dataroot> <Courses> <id>1</id> <name>Advanced C</name> </Courses> <id>102</id> <name>Algebra 1</name> <id>23</id> <name>Algebra 2</name> <id>100</id> <name>C++</name> <id>20</id> <name>Intro To C</name> <id>101</id> <name>Physics 2</name> </dataroot> AJAX | קבלת מידע מ- XML
56
AJAX | קבלת מידע מ- XML העיצוב מוגדר בקובץ CSS חיצוני:
57
<body onload="loadDoc('26_courses.xml', updateCoursesTable)">
<h2>My Courses Data</h2> <div id="tableData"></div> <script> function loadDoc(theUrl, theFunc) { ... } function updateCoursesTable(xhttp) { var xmlDoc = xhttp.responseXML; var table = '<div style="overflow-x:auto;"><table style=\"width:30%;\">'; table += "<tr><th>Id</th><th>Name</th></tr>"; var allCourses = xmlDoc.getElementsByTagName("Courses"); for (var i = 0; i < allCourses.length; i++) { table += "<tr><td>" + allCourses[i].getElementsByTagName("id")[0].childNodes[0].nodeValue + "</td><td>" + allCourses[i].getElementsByTagName("name")[0].childNodes[0].nodeValue + "</td></tr>"; table += '</table></div>'; document.getElementById("tableData").innerHTML = table; </script> <dataroot> <Courses> <id>1</id> <name>Advanced C</name> </Courses> … </dataroot>
58
טעינת תוכן אתר שלם מ- XML
למשל אם יש אתר המכיל קטעי מידע במבנה ועיצוב זהה
59
מימוש רע – כל התוכן נמצא ב- HTML
מימוש רע – כל התוכן נמצא ב- HTML מימוש רע מאחר ועדכון שם של class או המבנה ההיררכי של המידע, יגרור עדכון בכל חלקיו
60
מימוש טוב – הפרדה בין התוכן לאופן הצגתו
במימוש זה התוכן יהיה ב- XML ולא יכלול את המבנה ההיררכי של האלמנטים והעיצוב היררכית המידע תיבנה באמצעות JavaScript ושימוש ב- DOM העיצוב יתבצע באמצעות CSS הדגש הוא על שימוש בסלקטורים מסוג class
61
XML עם התוכן
62
שימוש ב- DOM לבניית מבנה התוכן
שימוש ב- DOM לבניית מבנה התוכן המבנה ההיררכי של ה- HTML מוגדר פעם אחת וחוזר על עצמו בלולאה
63
קישור לדוגמאות קוד פופולאריות
64
ביחידה זו למדנו: DOM סוגי פלטים שונים עדכון HTML באמצעות JS פונקציות
הוספה והסרת אירועים עדכון HTML באמצעות JS DOM navigation פונקציות BOM מספר משתנה של פרמטרים גישה לדפדפן ולמסך Closures מידע על ה- URL אירועים Pop-ups this Timer טווח הכרה של משתנים Cookies מחרוזות AJAX אובייקטים XML מערכים
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.