




版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、Application: Decision Helper IN THIS CHAPTER Multiple frames Multiple-document applications Multiple windows Persistent storage (cookies) Scripted image maps Scripted charts T he list of key concepts for this chapters application looks like the grand fi nale to a fi reworks show. As JavaScript imple
2、mentations go, this application is, in some respects, over the top, yet not out of the question for presenting a practical interactive application on a web site with- out any server programming. The Application I wanted to implement a classic application often called a decision support sys- tem. My
3、experience with the math involved here goes back to the fi rst days of Microsoft Excel. Rather than design a program that had limited appeal (covering only one possible decision tree), I set out to make a completely user-customizable decision helper. All the user has to do is enter values into fi el
4、ds on a series of screens; the program performs the calculations to let the user know how the various choices rank against each other. Although I wont be delving too deeply into the math inside this application, you will fi nd it helpful to understand how a user approaches this program and what the
5、results look like. The basic scenario is a user who is trying to evaluate how well a selection of choices measure up to his or her expecta- tions of performance. User input includes: ?The name of the decision ? The names of up to fi ve alternatives (people, products, ideas, and so on) ?The factors o
6、r features of concern to the user ?The importance of each of the factors to the user ?A user ranking of the performance of every alternative in each factor BC715 Part VIII: Applications What makes this kind of application useful is that it forces the user to rate and weigh a number of often-confl ic
7、ting factors. By assigning hard numbers to these elements, the computer calculates a decision based on the rates and weights of the various factors. Results come in the form of fl oating-point numbers between 0 and 100. As an extra touch, Ive added a graphical charting component to the results displ
8、ay. The Design With so much user input necessary for this application, conveying the illusion of simplicity is important. Rather than lump all text objects onto a single scrolling page, I decided to break them into fi ve pages, each consisting of its own HTML document. As an added benefi t, I could
9、embed information from early screens into the HTML of later screens, which would help to establish a more intuitive user interface. This good idea presented one opportunity and one rather large challenge. The opportunity was to turn the interface for this application into something resembling a mult
10、i- media application using multiple frames. The largest frame would contain the forms the user fi lls out, as well as the results page. Another frame would contain a navigation panel with arrows for moving forward and backward through the sequence of screens, plus buttons for going back to a home pa
11、ge and getting information about the program. I also thought a good idea would be to add a frame that provides instructions or suggestions for the users at each step. And so, the three-frame window was born, as shown in the fi rst entry screen in Figure 58-1. Using a navigation bar also enables me t
12、o demonstrate how to script a client-side image map not an obvious task with JavaScript. Also notice in the fi gure how there is a helpful text message appearing just above the navigation bar. This tooltip-style message appears thanks to the use of several handyonmouseoverandonmouseoutevent handlers
13、, which you learn about a bit later in the chapter. On the challenge side of this design, fi nding a way to maintain data globally, as the user navi- gates from screen to screen, was necessary. Every time one of the entry pages unloads, none of its text fi elds is available to a script. My fi rst at
14、tack at this problem was to store the data as global variable data (mostly arrays) in the parent document that creates the frames. Because JavaScript enables you to reference any parent documents object, function, or variable (by preceding the reference withparent), I thought this task would be a sn
15、ap. But a hazard exists in that a reload of the frameset could erase the current state of those variables. My next hope was to use thedocument.cookieas the storage bin for the data. A major problem I faced was that this program needs to store a total of 41 individual data points, yet no more than 20
16、 uniquely-named cookies can be allotted to a given domain. (While some modern browsers dont have a limit, other modern browsers and legacy browsers allow between 20 and 50 cookies.) But the cookie proved to be the primary solution for this application. (See the Further Thoughts section at the end of
17、 the chapter about a non-cookie version on the BC716 Chapter 58: Application: Decision Helper CD-ROM.) For some of the data points (which are related in an array-like manner), I fashioned my own data structures so that one named cookie could contain up to fi ve related data points. That reduced my c
18、ookie demands to 17. FIGURE 58-1 The Decision Helper window consists of three frames. Note Testing the sample application obviously requires that cookies be enabled in your browser. Be aware that if you are testing with Google Chrome, your code will not work unless the fi les are coming from an HTTP
19、 server. Chrome intentionally disables cookies onfile:/documents. See Chapter 29, The Document and Body Objects, for a discussion of cookies. ? The Files Before I get into the code, let me explain the fi le structure of this application. Table 58-1 gives a rundown of the fi les used in the Decision
20、Helper. BC717 Part VIII: Applications TABLE 58-1 Files Comprising the Decision Helper Application FileDescription index.htmlFramesetting parent document dhNav.htmlNavigation bar document for the upper-left frame that contains some scripting dhNav.gifImage displayed in dhNav.html dh1.htmlFirst Decisi
21、on Helper entry page dh2.htmlSecond Decision Helper entry page dh3.htmlThird Decision Helper entry page dh4.htmlFourth Decision Helper entry page dh5.htmlResults page chart.gif Tiny image fi le used to create bar charts in dh5.html dhHelp.htmlSample data and instructions document for the lower frame
22、 dhAbout.htmlDocument that loads into a second window A great deal of interdependence exists among these fi les. As you see later, assigning the names to some of these fi les was strategic for the implementation of the image map. The Code With so many JavaScript-enhanced HTML documents in this appli
23、cation, you can expect a great deal of code. To best grasp whats going on here, fi rst try to understand the structure and inter- play of the documents, especially the way the entry pages rely on functions defi ned in the parent document. My goal in describing this structure is not to teach you how
24、to implement this appli- cation, but rather how to apply the lessons I learned while building this application to the more complex ideas that may be aching to get out of your head and into JavaScript. index.html Taking a top-down journey through the JavaScript and HTML of the Decision Helper, start
25、at the document that loads the frames. Unlike a typical framesetting document, however, this one contains JavaScript code in itsheadsection code that many other documents rely on: Decision Helper BC718 Chapter 58: Application: Decision Helper An important consideration to remember is that in a multi
26、ple-frame environment, the title of the parent windows document is the name that appears in the windows title bar, no matter how many other documents are open inside its subframes. The fi rst items of the script control a global variable,currTitle, which is set by a number of the subsidiary fi les a
27、s the user navigates through the application. This variable ultimately helps the navigation bar buttons do their jobs correctly. Because this application relies on the document.cookie so heavily, the cookie management functions (slightly modifi ed versions of Bill Dortchs cookie functions see Chapte
28、r 29) are located in the parent document so they load only once. I simplifi ed the cookie-writing function because this application uses default set- tings for pathname and expiration. With no expiration date, the cookies dont survive the current browser session, which is perfect for this applicatio
29、n: / global variable settings of current dh document number var currTitle = ; function setTitleVar(titleVal) currTitle = + titleVal; function getCookieVal(offset) var endstr = document.cookie.indexOf (;, offset); if ( + endstr) = | endstr = -1) endstr = document.cookie.length; return unescape(docume
30、nt.cookie.substring(offset, endstr); function getCookie(name) var arg = name + =; var alen = arg.length; var clen = document.cookie.length; var i = 0; while (i clen) var j = i + alen; if (document.cookie.substring(i, j) = arg) return getCookieVal (j); i = document.cookie.indexOf( , i) + 1; if (i = 0
31、) break; return null; BC719 Part VIII: Applications function setCookie(name, value) document.cookie = name + = + escape (value) + ; When this application loads (or a user elects to start a new decision), its important to grab the cookies you need and initialize them to the basic values that the entr
32、y screens will use to fi ll fi elds when the user fi rst visits them. All statements inside theinitializeCookies() function call thesetCookie() function, defi ned in the preceding listing. The parameters are the name of each cookie and the initial value mostly empty strings. Before going on, study t
33、he cookie labeling structure carefully. I refer to it often in discussions of other documents in this application: function initializeCookies() setCookie(decName,); setCookie(alt0,); setCookie(alt1,); setCookie(alt2,); setCookie(alt3,); setCookie(alt4,); setCookie(factor0,); setCookie(factor1,); set
34、Cookie(factor2,); setCookie(factor3,); setCookie(factor4,); setCookie(import,0); setCookie(perf0,); setCookie(perf1,); setCookie(perf2,); setCookie(perf3,); setCookie(perf4,); The following functions should look familiar to you. They were borrowed either wholesale or with minor modifi cation from th
35、e data-entry validation section of the Social Security number database lookup in Chapter 53, Application: A Lookup Table. Im glad I wrote these as generic functions, making them easy to incorporate into this script. Because many of the entry fi elds on two screens must be integers between 1 and 100,
36、 I brought the data validation functions to the parent document rather than duplicating them in each of the subdocuments: / JavaScript sees numbers with leading zeros / as octal values, so strip zeros function stripZeros(inputStr) var result = inputStr; while (result.substring(0,1) = 0) result = res
37、ult.substring(1,result.length); return result; BC720 Chapter 58: Application: Decision Helper / general purpose function to see if a suspected numeric / input is a positive integer function isNumber(inputStr) for (var i = 0; i inputStr.length; i+) var oneChar = inputStr.substring(i, i + 1); if (oneC
38、har 9) return false; return true; / function to determine if value is in acceptable / range for this application function inRange(inputStr) num = parseInt(inputStr); if (num 100) return false; return true; To control the individual data entry validation functions in the master controller, I again wa
39、s able to borrow heavily from the application in Chapter 53: / Master value validator routine function isValid(inputStr) if (inputStr != ) inputStr = stripZeros(inputStr); if (!isNumber(inputStr) alert(Please make sure entries are numbers only.); return false; else if (!inRange(inputStr) var msg=Ent
40、ries must be numbers between 1 and 100.; msg += Try another value.; alert(msg); return false; return true; BC721 Part VIII: Applications Each of the documents containing entry forms retrieves and stores information in the cookie. Because all cookie functions are located in the parent document, it si
41、mplifi es coding in the sub- ordinate documents to have functions in the parent document acting as interfaces to the primary cookie functions. For each category of data stored as cookies, the parent document has a pair of functions for getting and setting data. The calling statements pass only the d
42、ata to be stored when saving information; the interface functions handle the rest, such as storing or retrieving the cookie with the correct name. In the following pair of functions, the decision name (from the fi rst entry document) is passed back and forth between the cookie and the calling statem
43、ents. Not only must the script store the data, but if the user returns to that screen later for any reason, the entry fi eld must retrieve the previously entered data: function setDecisionName(str) setCookie(decName,str); function getDecisionName() return getCookie(decName); The balance of the stora
44、ge and retrieval pairs does the same thing for their specifi c cookies. Some cookies are named according to index values (factor1,factor2, and so on), so their cookie-accessing functions require parameters for determining which of the cookies to access, based on the request from the calling statemen
45、t. Many of the cookie retrieval functions are called to fi ll in the data in tables of later screens during the users trip down the decision path: function setAlternative(i,str) setCookie(alt + i,str); function getAlternative(i) return getCookie(alt + i); function setFactor(i,str) setCookie(factor +
46、 i,str); function getFactor(i) return getCookie(factor + i); function setImportance(str) setCookie(import,str); function getImportance(i) BC722 Chapter 58: Application: Decision Helper return getCookie(import); function setPerformance(i,str) setCookie(perf + i,str); function getPerformance(i) return
47、 getCookie(perf + i); One sequence of code that runs when the parent document loads is the one that looks to see if a cookie structure is set up. If no such structure is set up (the retrieval of a designated cookie returns anullvalue), the script initializes all cookies via the function described ea
48、rlier: if (getDecisionName() = null) initializeCookies(); The last part of the script is a function thats called if the user wants to plug in a canned example by clicking a button in the fi le (dh1.html ) that is the fi rst data entry screen in the upper-right frame: / plug in sample code if user wa
49、nts function doSample(form) setCookie(decName,Buying a FAX machine); setCookie(alt0,Fax-O-Matic 1000); setCookie(alt1,InkyFax 300); setCookie(alt2,LazyFax LX); setCookie(alt3,Loose Cannon M-200); setCookie(alt4,); setCookie(factor0,Cost); setCookie(factor1,Size); setCookie(factor2,Paper Handling); s
50、etCookie(factor3,Warranty); setCookie(factor4,); setCookie(import,0.); setCookie(perf0,0.); setCookie(perf1,0.); setCookie(perf2,0.); setCookie(perf3,0.); setCookie(perf4,); parent.entryForms.document.forms0.decName.value = Buying a FAX machine; The
51、balance of the parent document source code defi nes the frameset for the browser window. It establishes some hard-wired pixel sizes for the navigation panel. This ensures that the entire BC723 Part VIII: Applications .gif fi le is visible whenever the frameset loads, without a ton of unwanted white
52、space if the browser window is large: Its really cool. .but only if your browser handles frames Back Its worth pointing out that some older browsers do not respond to changes in framesetting size attributes through a simple reload of the page. Modern browsers appear to have resolved this problem; ho
53、wever if you seem to be making changes, but reloading the frameset doesnt make the changes appear, try reopening the browser window or as a last resort restarting the browser. dhNav.html Because of its crucial role in controlling the activity around this program, look into the navi- gation bars docu
54、ment next. To accomplish the look and feel of a multimedia program, this document was designed as a client-side image map that has four regions scripted, correspond- ing to the locations of the four buttons (see Figure 58-1). The trick to the tooltip mechanism is the showing and hiding of adivelemen
55、t that contains the text to be displayed. This element has its own style class,tipStyle, which is responsible for establishing the white rectangular text box with a thin black border. Navigation Bar body background-color:white; .tipStyle position:absolute; BC724 Chapter 58: Application: Decision Hel
56、per background-color:#FFFFFF; border:solid 1px #000000; padding:2px; visibility: hidden; One function is connected to each button. The fi rst function is linked to the graphical Home button. For the listing here, I just present an alert dialog box replicating the action of navigating back to a real
57、web sites home page: function goHome() alert(Navigate back to home page on a real site.); Each of the arrow navigation buttons brings the user to the next or previous entry screen in the sequence. To facilitate this without building tables of document titles and names, you call upon thecurrTitleglob
58、al variable in the parent document. This value contains an integer in the range between 1 and 5, corresponding to the main content documentsdh1.html,dh2.html, and so on. As long as the offset number is no higher than the next-to-last document in the sequence, thegoNext()function increments the index value by one and concatenates a new location for the frame. At the same time, the script advances the help document (in the bottom fr
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 外包运输劳务合同范本
- 房产365租房合同范本
- 大件搬运维修合同范本
- 食堂档口合同范本
- 农产品溯源体系在2025年农业产业扶贫中的应用报告
- 图书漂流试题及答案
- 锅炉制造试题及答案
- 写材料短语题目及答案
- 2025年初二函数题库及答案
- 光伏组件技能考试试题及答案
- JJG 539-2016数字指示秤
- 辽宁盘锦浩业化工“1.15”泄漏爆炸着火事故警示教育
- GB 25585-2010食品安全国家标准食品添加剂氯化钾
- 小学信息技术人工智能教学案例
- 服装零售业概况
- sg1000系列光伏并网箱式逆变器通信协议
- 专升本03297企业文化历年试题题库(考试必备)
- 第四讲大学生就业权益及其法律保障课件
- 重庆大学介绍课件
- 学校开展校园欺凌专项治理情况自查表
- 电能表生产流程
评论
0/150
提交评论