בתרגול זה, תתבקשו ליישם את מה שלמדתם בכל המאמרים האחרונים במודול הנוכחי על מנת ליצור יישום קטן שמייצר סיפורים טיפשיים באופן רנדומלי.
ידע מוקדם: | אנא וודאו כי עברתם על כל המאמרים במודול זה בטרם ביצוע התרגול. |
---|---|
מטרה: | לוודא הבנה של יסודות שפת JavaScript ושימוש במשתנים, מספרים,אופרטורים, מחרוזות ומערכים. |
נקודת התחלה
על מנת להתחיל:
- הורידו את הקובץ זה לצורך התרגול ושמרו אותו בשם
index.html
בתיקיה במחשב שלכם. קובץ זה מכיר גם CSS על מנת לעצב את הדוגמא שנמצאת בתוכו. - גשו ל דף המכיל מידע גולמי והשאירו אותו פתוח בלשונית חדשה בדפדפן שלכם. אתם תצטרכו אותו אחר כך.
תקציר הפרוייקט
קיבלתם לידיכם HTML/CSS גולמי ומס׳ מחרווזת טקסט וכן מס׳ פונקציות של JavaScript. הנכם נדרשים לכתוב את הקוד הרלוונטי על מנת להפוך אותם לתוכנית שעושה את הדברים הבאים:
- יוצרת סיפור חדש כאשר הכפתור "Generate random story" נלחץ.
- מחליפה את שם ברירת המחדל "Bob" אשר נמצא בסיפור, בשם אחר, רק אם השם האחר הוכנס לתוך תיבת הטקסט "Enter custom name" לפני שכפתור יצירת הסיפור נלחץ.
- ממירה את שיטת המשקלים והטמפרטורות משיטה אמריקאית לשיטה בריטית אם הכפתור uk מסומן לפני שנלחץ על כפתור יצירת הסיפור.
- נייצר סיפור אקראי בכל פעם אם תלחץ על הכפתור שוב (ושוב...)
צילום המסך הבא יסייע לכם להבין כיצד זה אמור להיראות:
לתת לכם קצת יותר הכוונה, הסתכלו בפתרון העובד (אך אל תסתכלו על קוד המקור, אלא אם ממש נתקעתם)
פעולות נדרשות
אלו הפעולות שתידשו לבצע על מנת להשלים את התרגול בהצלחה
התקנה בסיסית:
- צרו קובץ חדש שנקרא בשם
main.js
, באותה תיקיה שבה נמצא קובץindex.html
שלכם - החילו את קובץ ה-JavaScript לתוך קובץ ה-HTML כפי שלמדנו באמצעות
<script>
עם קישור ל-main.js
. שימו אותו לפני תגית הסיום של</body>
.
אתחול משתנים ופונקציות:
- בקובץ הטקסט הגולמי העתיקו את כל הקוד שמופיע תחת הכותרת "1. COMPLETE VARIABLE AND FUNCTION DEFINITIONS" והדביקו אותו בחלקו העליון של הקובץ
main.js
.זה נותן שלשה משתנים שמכילים הפניות לשדה הטקסט "Enter custom name" (המשתנה:customName
) ולכפתור "Generate random story" (המשתנה:randomize
) ולאלמנט<p>
(המשתנה:story
) שבתחתית חלק ה HTML שאליו יועתק הסיפור בהתאמה. בנוסף יש לך פונקציה שנקראתrandomValueFromArray()
שלוקחת מערך, ומחזירה אחד מהפריטים המאוחסנים בתוך המערך באופן אקראי - כעת התבוננו בקטע השני שבקובץ הטקסט הגולמי "2. RAW TEXT STRINGS" זה מכיל מחרוזות טקסט that will act as input into our program. We'd like you to contain these inside variables inside
main.js
:- Store the third set of three strings inside an array called
insertZ
. - Store the second set of three strings inside an array called
insertY
. - Store the first set of three strings inside an array called
insertX
. - Store the first, big long, string of text inside a variable called
storyText
.
- Store the third set of three strings inside an array called
Placing the event handler and incomplete function:
- Now return to the raw text file.
- Copy the code found underneath the heading "3. EVENT LISTENER AND PARTIAL FUNCTION DEFINITION" and paste it into the bottom of your
main.js
file. This:- Adds a click event listener to the
randomize
variable so that when the button it represents is clicked, theresult()
function is run. - Adds a partially-completed
result()
function definiton to your code. For the remainder of the assessment, you'll be filling in lines inside this function to complete it and make it work properly.
- Adds a click event listener to the
Completing the result()
function:
- Create a new variable called
newStory
, and set it's value to equalstoryText
. This is needed so we can create a new random story each time the button is pressed and the function is run. If we made changes directly tostoryText
, we'd only be able to generate a new story once. - Create three new variables called
xItem
,yItem
, andzItem
, and make them equal to the result of callingrandomValueFromArray()
on your three arrays (the result in each case will be a random item out of each array it is called on). For example you can call the function and get it to return one random string out ofinsertX
by writingrandomValueFromArray(insertX)
. - Next we want to replace the three placeholders in the
newStory
string —:insertx:
,:inserty:
, and:insertz:
— with the strings stored inxItem
,yItem
, andzItem
. There is a particular string method that will help you here — in each case, make the call to the method equal tonewStory
, so each time it is called,newStory
is made equal to itself, but with substitutions made. So each time the button is pressed, these placeholders are each replaced with a random silly string. As a further hint, the method in question only replaces the first instance of the substring it finds, so you might need to make one of the calls twice. - Inside the first
if
block, add another string replacement method call to replace the name 'Bob' found in thenewStory
string with thename
variable. In this block we are saying "If a value has been entered into thecustomName
text input, replace Bob in the story with that custom name." - Inside the second
if
block, we are checking to see if theuk
radio button has been selected. If so, we want to convert the weight and temperature values in the story from pounds and Fahrenheit into stones and centigrade. What you need to do is as follows:- Look up the formulae for converting pounds to stone, and Fahrenheit to centigrade.
- Inside the line that defines the
weight
variable, replace 300 with a calculation that converts 300 pounds into stones. Concatenate' stone'
onto the end of the result of the overallMath.round()
call. - Inside the line that defines the
temperature
variable, replace 94 with a calculation that converts 94 Fahrenheit into centigrade. Concatenate' centigrade'
onto the end of the result of the overallMath.round()
call. - Just under the two variable definitions, add two more string replacement lines that replace '94 fahrenheit' with the contents of the
temperature
variable, and '300 pounds' with the contents of theweight
variable.
- Finally, in the second-to-last line of the function, make the
textContent
property of thestory
variable (which references the paragraph) equal tonewStory
.
רמזים וטיפים
- You don't need to edit the HTML in any way, except to apply the JavaScript to your HTML.
- If you are unsure whether the JavaScript is applied to your HTML properly, try removing everything else from the JavaScript file temporarily, adding in a simple bit of JavaScript that you know will create an obvious effect, then saving and refreshing. The following for example turns the background of the
<html>
element red — so the entire browser window should go red if the JavaScript is applied properly:document.querySelector('html').style.backgroundColor = 'red';
- Math.round() is a built-in JavaScript method that simply rounds the result of a calculation to the nearest whole number.
- There are three instances of strings that need to be replaced. You may repeat the
replace()
method multiple times, or you can use regular expressions. For instance,var text = 'I am the biggest lover, I love my love'; text.replace(/love/g,'like');
will replace all instances of 'love' to 'like'. Remember, Strings are immutable!
Assessment
If you are following this assessment as part of an organized course, you should be able to give your work to your teacher/mentor for marking. If you are self-learning, then you can get the marking guide fairly easily by asking on the discussion thread for this exercise, or in the #mdn IRC channel on Mozilla IRC. Try the exercise first — there is nothing to be gained by cheating!