1. Trang chủ
  2. » Công Nghệ Thông Tin

Beginning JavaScript Third Edition phần 10 doc

80 521 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 80
Dung lượng 0,96 MB

Nội dung

Well, that would work, but it would also replace the a in “walked,” which you don’t want. You want to replace the letter a, but only where it’s a word on its own and not inside another word. So when does a letter become a word? The answer is when it’s between two word boundaries. The word boundary is represented by the regular expression special character \b, so the regular expression becomes this: var myRegExp = /\ba\b/gi; The gi at the end ensures a global, case-insensitive search. Now, with your regular expression created, you can use it in the replace() method’s first parameter. myString = myString.replace(myRegExp,”the”); Question 3 Imagine you have a website with a message board. Write a regular expression that would remove barred words. (You can make up your own words.) Solution <html> <body> <script language=”JavaScript” type=”text/javascript”> var myRegExp = /(sugar )?candy|choc(olate|oholic)?/gi; var myString = “Mmm, I love chocolate, I’m a chocoholic. “ + “I love candy too, sweet, sugar candy”; myString = myString.replace(myRegExp,”salad”); alert(myString) </script> </body> </html> Save this as ch08_q3.htm. For this example, pretend you’re creating script for a board on a dieting site where text relating to candy is barred and will be replaced with references to a much healthier option, salad. The barred words are: ❑ chocolate ❑ choc ❑ chocoholic ❑ sugar candy ❑ candy Let’s see how you can build up the regular expression to remove the offending words. 688 Appendix A: Exercise Solutions 20_051511 appa.qxp 4/13/07 6:23 PM Page 688 Start with the two basic words, so to match choc or candy, use this: candy|choc Next, add the matching for sugar candy. Since the sugar bit is optional, you group it by placing it in parentheses and adding the question mark after it. This means “Match the group zero times or one time.” (sugar )?candy|choc Finally you need to add the optional olate and oholic end bits. You add these as a group after the “choc” word and again make the group optional. You can match either of the endings in the group by using the | character. (sugar )?candy|choc(olate|oholic)?/gi Finally, you declare it as follows: var myRegExp = /(sugar )?candy|choc(olate|oholic)?/gi The gi at the end means that the regular expression will find and replace words on a global, case- insensitive basis. So, to sum up: /(sugar )?candy|choc(olate|oholic)?/gi reads as: Either match zero or one occurrences of “sugar” followed by “candy.” Or alternatively match “choc” followed by either one or zero occurrences of “olate” or match “choc” followed by zero or one occurrence of “oholic.” Finally, the following: myString = myString.replace(myRegExp,”salad”); replaces the offending words with “salad” and sets myString to the new clean version: “Mmm, I love salad, I’m a salad. I love salad too, sweet, salad.” Chapter 9 In this chapter you looked in more detail at the Date object, particularly with respect to world time and local time. You also looked at how to create timers to trigger code on a web page. 689 Appendix A: Exercise Solutions 20_051511 appa.qxp 4/13/07 6:23 PM Page 689 Question 1 Create a web page with an advertisement image at the top. When the page loads, select a random image for that advertisement. Every four seconds, make the image change to a different one, making sure a dif- ferent advertisement is selected until all the advertisement images have been seen. Solution <html> <head> <script language=”JavaScript” type=”text/javascript”> var imagesSelected = new Array(false,false,false); var noOfImages = 3; var totalImagesSelected = 0; function window_onload() { setInterval(“switchImage()”,4000); } function switchImage() { var imageIndex; if (totalImagesSelected == noOfImages) { for (imageIndex = 0; imageIndex < noOfImages; imageIndex++) { imagesSelected[imageIndex] = false; } totalImagesSelected = 0; } var selectedImage = Math.floor(Math.random() * noOfImages) + 1; while (imagesSelected[selectedImage - 1] == true) { selectedImage = Math.floor(Math.random() * noOfImages) + 1; } totalImagesSelected++; imagesSelected[selectedImage - 1] = true; document.imgAdvert.src = “AdvertImage” + selectedImage + “.jpg”; } </script> </head> <body onload=”window_onload()”> <img src=”AdvertImage1.jpg” name=”imgAdvert”> </body> </html> 690 Appendix A: Exercise Solutions 20_051511 appa.qxp 4/13/07 6:23 PM Page 690 Save this as ch09_q1.htm. This solution is based on the example in the chapter, Adverts.htm, in which you displayed three images at set intervals, one after the other. The first difference is that you select a random image each time, rather than the images in sequence. Secondly, you make sure you don’t select the same image twice in one sequence by having an array, imagesSelected, with each element of that array being true or false depending on whether the image has been selected before. Once you’ve shown each image, you reset the array and start the sequence of selecting images randomly again. The final difference between this solution and the example in the chapter is that you set the timer going continuously with setInterval(). So until the user moves to another page, your random display of images will continue. Question 2 Create a form that gets the user’s date of birth. Then, using that information, tell her on what day of the week she was born. Solution <html> <head> <script language=”JavaScript” type=”text/javascript”> var days = new Array(); days[0] = “Sunday”; days[1] = “Monday”; days[2] = “Tuesday”; days[3] = “Wednesday”; days[4] = “Thursday”; days[5] = “Friday”; days[6] = “Saturday”; function dayOfWeek() { var form = document.form1; var date = parseInt(form.txtDate.value) var year = parseInt(form.txtYear.value) if (isNaN(date) || isNaN(year)) { alert(“Please enter a valid whole number”); } else { if (date < 1 || date > 31) { alert(“Day of the month must be between 1 and 31”); } else 691 Appendix A: Exercise Solutions 20_051511 appa.qxp 4/13/07 6:23 PM Page 691 { userDate = date + “ “; userDate = userDate + form.selMonth.options[form.selMonth.selectedIndex].value; userDate = userDate + “ “ + year; var dateThen = new Date(userDate); alert(days[dateThen.getDay()]); } } } </script> </head> <body> <P>Find the day of your birth</P> <P> <form name=”form1”> <input type=”text” name=”txtDate” size=”2” maxlength=”2”> <select name=selMonth> <option selected value=”Jan”>Jan</option> <option selected value=”Feb”>Feb</option> <option selected value=”Mar”>Mar</option> <option selected value=”Apr”>Apr</option> <option selected value=”May”>May</option> <option selected value=”Jun”>Jun</option> <option selected value=”Jul”>Jul</option> <option selected value=”Aug”>Aug</option> <option selected value=”Sept”>Sept</option> <option selected value=”Oct”>Oct</option> <option selected value=”Nov”>Nov</option> <option selected value=”Dec”>Dec</option> </select> <input type=text name=txtYear size=4 maxlength=4> <br> <input type=”button” value=”Day of the week” onclick=”dayOfWeek()” name=”button1”> </form> </P> </body> </html> Save this as ch09_q2.htm. The solution is surprisingly simple. You create a new Date object based on the date entered by the user. Then you get the day of the week using the Date object’s getDay() method. This returns a number, but by defining an array of days of the week to match this number, you can use the value of getDay() as the index to your days array. You also do some basic sanity checking to make sure that the user has entered numbers and that in the case of the date, the number is between 1 and 31. You could have defined a select element as the method of getting the date and only have numbers from 1 to 31. Of course, for either way, you don’t check 692 Appendix A: Exercise Solutions 20_051511 appa.qxp 4/13/07 6:23 PM Page 692 whether invalid dates are entered (for example, the 31st of February). You might want to try this as an additional exercise. Hint: To get the last day of the month, get the first day of the next month and then subtract one. Chapter 10 In this chapter you looked at some common mistakes in JavaScript code, debugging code using the Microsoft script debugger, and ways of handling errors using the try catch clause and the throw statement. Question 1 The example debug_timestable2.htm has a deliberate bug. For each times table it creates only multi- pliers with values from 1 to 11. Use the script debugger to work out why this is happening, and then correct the bug. Solution The problem is with your code’s logic rather than its syntax. Logic errors are much harder to spot and deal with because, unlike with syntax errors, the browser won’t inform you that there’s such and such error at line so and so but instead just fails to work as expected. The error is with this line: for (counter = 1; counter < 12; counter++) You want your loop to go from 1 to 12 inclusive. Your counter < 12 statement will be true up to and including 11 but will be false when the counter reaches 12; hence 12 gets left off. To correct this, you could change your code to the following: for (counter = 1; counter <= 12; counter++) Question 2 The following code contains a number of common errors. See if you can spot them: <html> <head> </head> <body> <script language=JavaScript> function checkForm(theForm) { var formValid = true; var elementCount = 0; while(elementCount =< theForm.length) { 693 Appendix A: Exercise Solutions 20_051511 appa.qxp 4/13/07 6:23 PM Page 693 if (theForm.elements[elementcount].type == “text”) { if (theForm.elements[elementCount].value() = “”) alert(“Please complete all form elements”) theForm.elements[elementCount].focus; formValid = false; break; } } return formValid; } </script> <form name=form1 onsubmit=”return checkForm(document.form1)”> <input type=”text” ID=text1 name=text1> <br> CheckBox 1<input type=”checkbox” ID=checkbox1 name=checkbox1> <br> CheckBox 2<input type=”checkbox” ID=checkbox2 name=checkbox2> <br> <input type=”text” ID=text2 name=text2> <p> <input type=”submit” value=”Submit” ID=submit1 name=submit1> </p> </form> </body> </html> Solution The bug-free version looks like this: <html> <head> </head> <body> <script language=”JavaScript”> function checkForm(theForm) { var formValid = true; var elementCount = 0; while(elementCount < theForm.length) { if (theForm.elements[elementCount].type == “text”) { if (theForm.elements[elementCount].value == “”) { alert(“Please complete all form elements”) theForm.elements[elementCount].focus(); formValid = false; break; 694 Appendix A: Exercise Solutions 20_051511 appa.qxp 4/13/07 6:23 PM Page 694 } } elementCount++; } return formValid; } </script> <form name=”form1” onsubmit=”return checkForm(document.form1)”> <input type=”text” id=”text1” name=”text1”> <br> CheckBox 1<input type=”checkbox” id=”checkbox2” name=”checkbox2”> <br> CheckBox 1<input type=”checkbox” id=”checkbox1” name=”checkbox1”> <br> <input type=”text” id=”text2” name=”text2”> <P> <input type=”submit” value=”Submit” id=”submit1” name=”submit1”> </P> </form> </body> </html> Let’s look at each error in turn. The first error is a logic error. while(elementCount =< theForm.length) Arrays start at 0 so the first Form object is at index array 0, the second at 1, and so on. The last Form object has an index value of 4. However, theForm.length will return 5 because there are five elements in the form. So the while loop will continue until elementCount is less than or equal to 5, but as the last element has an index of 4, this is one past the limit. You should write either this: while(elementCount < theForm.length) or this: while(elementCount <= theForm.length - 1) Either is fine, though the first is shorter. You come to your second error in the following line: if (theForm.elements[elementcount].type == “text”) 695 Appendix A: Exercise Solutions 20_051511 appa.qxp 4/13/07 6:23 PM Page 695 On a quick glance it looks fine, but it’s JavaScript’s strictness on case sensitivity that has caused your downfall. The variable name is elementCount, not elementcount with a lowercase c. So this line should read as follows: if (theForm.elements[elementCount].type == “text”) The next line with an error is this: if (theForm.elements[elementCount].value() = “”) This has two errors. First, value is a property and not a method, so there is no need for parentheses after it. Second, you have the all-time classic error of one equals sign instead of two. Remember that one equals sign means “Make it equal to,” and two equals signs mean “Check if it is equal to.” So with the changes, the line is: if (theForm.elements[elementCount].value == “”) The next error is your failure to put your block of if code in curly braces. Even though JavaScript won’t throw an error since the syntax is fine, the logic is not so fine, and you won’t get the results you expect. With the braces, the if statement should be as follows: if (theForm.elements[elementCount].value == “”) { alert(“Please complete all form elements”) theForm.elements[elementCount].focus; formValid = false; break; } The penultimate error is in this line: theForm.elements[elementCount].focus; This time you have a method but with no parentheses after it. Even methods that have no parameters must have the empty parentheses after them. So, corrected, the line is as follows: theForm.elements[elementCount].focus(); Now you’re almost done; there is just one more error. This time it’s not something wrong with what’s there, but rather something very important that should be there but is missing. What is it? It’s this: elementCount++; This line should be in your while loop, otherwise elementCount will never go above 0 and the while loop’s condition will always be true, resulting in the loop continuing forever: a classic infinite loop. Chapter 11 In this chapter you looked at storing small amounts of information, called cookies, on the user’s com- puter and using that information to customize your web site for the user. 696 Appendix A: Exercise Solutions 20_051511 appa.qxp 4/13/07 6:23 PM Page 696 Question 1 Create a page that keeps track of how many times the page has been visited by the user in the last month. Solution <html> <head> <script language=”JavaScript” type=”text/javascript”> function getCookieValue(cookieName) { var cookieValue = document.cookie; var cookieStartsAt = cookieValue.indexOf(“ “ + cookieName + “=”); if (cookieStartsAt == -1) { cookieStartsAt = cookieValue.indexOf(cookieName + “=”); } if (cookieStartsAt == -1) { cookieValue = null; } else { cookieStartsAt = cookieValue.indexOf(“=”, cookieStartsAt) + 1; var cookieEndsAt = cookieValue.indexOf(“;”, cookieStartsAt); if (cookieEndsAt == -1) { cookieEndsAt = cookieValue.length; } cookieValue = unescape(cookieValue.substring(cookieStartsAt, cookieEndsAt)); } return cookieValue; } function setCookie(cookieName,cookieValue, cookiePath, cookieExpires) { cookieValue = escape(cookieValue); if (cookieExpires == “”) { var nowDate = new Date(); nowDate.setMonth(nowDate.getMonth() + 6); cookieExpires = nowDate.toGMTString(); } if (cookiePath != “”) { cookiePath = “;Path=” + cookiePath; } 697 Appendix A: Exercise Solutions 20_051511 appa.qxp 4/13/07 6:23 PM Page 697 [...]... docNavigate.appendChild(TableElem); docNavigate = docNavigate.lastChild; docNavigate.appendChild(THElem); docNavigate = docNavigate.firstChild; docNavigate.appendChild(TRElem1); docNavigate = docNavigate.firstChild; docNavigate.appendChild(TDElem1); docNavigate = docNavigate.firstChild; docNavigate.appendChild(TextNodeA1); docNavigate = docNavigate.nextSibling; docNavigate.appendChild(TextNodeA2); docNavigate = docNavigate.nextSibling;... the next TD element //Adds the third text node docNavigate = docNavigate.parentNode; docNavigate = docNavigate.parentNode; docNavigate = docNavigate.parentNode; docNavigate.appendChild(TBODYElem); docNavigate = docNavigate.lastChild; docNavigate.appendChild(TRElem2); docNavigate = docNavigate.lastChild; docNavigate.appendChild(TDElem4); docNavigate.appendChild(TDElem5); docNavigate.appendChild(TDElem6);... TD element docNavigate.appendChild(TDElem2); docNavigate.appendChild(TDElem3); 709 Appendix A: Exercise Solutions docNavigate = docNavigate.firstChild; docNavigate.appendChild(TextNodeB1); docNavigate = docNavigate.nextSibling; docNavigate.appendChild(TextNodeB2); docNavigate = docNavigate.nextSibling; docNavigate.appendChild(TextNodeB3); docNavigate = docNavigate.parentNode; docNavigate = docNavigate.parentNode;... docNavigate.parentNode; docNavigate.appendChild(TRElem3); docNavigate = docNavigate.lastChild; docNavigate.appendChild(TDElem7); docNavigate.appendChild(TDElem8); docNavigate.appendChild(TDElem9); docNavigate = docNavigate.firstChild; docNavigate.appendChild(TextNodeC1); docNavigate = docNavigate.nextSibling; docNavigate.appendChild(TextNodeC2); docNavigate = docNavigate.nextSibling; docNavigate.appendChild(TextNodeC3);... = document.createTextNode(“Price”) TextNodeB1 = document.createTextNode(“Chevrolet”) TextNodeB2 = document.createTextNode(“120mph”) TextNodeB3 = document.createTextNode(“ $10, 000”) TextNodeC1 = document.createTextNode(“Pontiac”) TextNodeC2 = document.createTextNode(“140mph”) TextNodeC3 = document.createTextNode(“$14,000”) docNavigate = document.documentElement; docNavigate = docNavigate.lastChild; docNavigate.appendChild(TableElem);... “Msxml2.DOMDocument.6.0”, “Msxml2.DOMDocument.3.0” ]; for (var i = 0; i < versions.length; i++) { try { xmlDoc = new ActiveXObject(versions[i]); return xmlDoc; } catch (error) { //do nothing here } } } //Create the DOM for Firefox and Opera else if (document.implementation && document.implementation.createDocument) { xmlDoc = document.implementation.createDocument(“”,””,null); return xmlDoc; } return... document.createElement(“TD”) TDElem3 = document.createElement(“TD”) TDElem4 = document.createElement(“TD”) TDElem5 = document.createElement(“TD”) TDElem6 = document.createElement(“TD”) TDElem7 = document.createElement(“TD”) TDElem8 = document.createElement(“TD”) TDElem9 = document.createElement(“TD”) TBODYElem = document.createElement(“TBODY”) TextNodeA1 = document.createTextNode(“Car”) TextNodeA2 = document.createTextNode(“Top... language= JavaScript > var TableElem = document.createElement(“table”) 708 Appendix A: Exercise Solutions var var var var var var var var var var var var var var var var var var var var var var var THElem = document.createElement(“thead”) TRElem1 = document.createElement(“TR”) TRElem2 = document.createElement(“TR”) TRElem3 = document.createElement(“TR”) TDElem1 = document.createElement(“TD”) TDElem2 = document.createElement(“TD”)... code to add a border: docAttr = document.getElementsByTagName(“table”).item(0); docAttr.setAttribute(“border”, “1”); Add these lines to the bottom of the script code to center-align headings: docNewAttr = document.getElementsByTagName(“thead”).item(0); docNewAttr.setAttribute(“align”, “center”); Chapter 14 In this chapter you took a very brief look at XML, created your first XML document (a DTD), and... } return null; } var xmlDoc = createDocument(); xmlDoc.load(“school.xml”); function writeTableOfSchoolChildren() { var xmlNode = xmlDoc.getElementsByTagName(‘child’); var newTableElement = document.createElement(‘table’); newTableElement.setAttribute(‘cellPadding’,5); var tempElement = document.createElement(‘tbody’); newTableElement.appendChild(tempElement); var tableRow = document.createElement(‘TR’); . startTimer() { floatingDiv = document.getElementById(“floatingDiv”); screenWidth = document.body.clientWidth; screenHeight = document.body.clientHeight; window.setInterval(“moveDiv()”, 10) ; } function moveDiv(). startTimer() { floatingDiv = document.getElementById(“floatingDiv”); screenWidth = document.body.clientWidth; screenHeight = document.body.clientHeight; window.setInterval(“moveDiv()”, 10) ; } 705 Appendix. hidden; } </style> <script type=”text /javascript > function showBoxOne() { var boxOne = document.getElementById(“boxOne”); var boxTwo = document.getElementById(“boxTwo”); boxOne.style.visibility

Ngày đăng: 09/08/2014, 14:21

TỪ KHÓA LIÊN QUAN