在浏览器上保存数据(转)[@more@]
JavaScript 能做的事,并不局限于访问HTML 表单的数据;它还能让你创建自己的对象――也就是让你创建储存于客户端的数据。你甚至还能建立包含其它对象的对象。
为什么需要这些功能?一个好的理由就是创建数组(array)。简单来说,数组是一个含有几组相关信息的表格或数据库。在下面的例子当中,我们定义了一个叫做taxTable的对象,该对象包含一个数组,而该数组由五个 name 对象实例所组成。这个数组保存五个州的州名,以及它们相关的税率。然后,当用户在订购表单中输入州名时,我们就在数组中检查它,并自动应用正确的税率。 创建一个5x2的数组,与使用一个快速的 if-then 序列来测试州名相比,使用数组似乎还要做额外的工作。不过,随着条目个数的增加,数组的功能也就变得愈来愈强大。不妨想象有一个拥有五十个州、或五百个销售区、亦或是五千个城市的表格。有了一个数组,你就能够一次建立条目列表,然后每当用户输入新数据时,就可迅速加以引用这个条目列表。 下面这个特殊的JavaScript 代码,开始就像我们的计算(calculation)示例一样。不过这一次,我们并不止于简单的数学计算: function state(stateName, stateTax){ //fill the instance with the values passed in this.name=stateName; this.tax=stateTax; //then return the instance of state return this; }上面定义的state() 函数创建了包括州名与税率的一个州(state)的实例。然而,我们的州此时似乎什么值都没有。下面我们给它们一些值吧。
function taxTable(){
//the instance of taxTable is filled with //an array of state objects this[0]=new state("AZ", 0.04); this[1]=new state("HI", 0.10); this[2]=new state("TX", 0.06); this[3]=new state("NJ", 0.08); this[4]=new state("", 0.00); //return the newly created taxTable to //the calling function return this; }现在,无论taxTable函数何时被调用,我们都创建了五个不同的州实例,分别编号为0到4。这样一来,我们就创建了一个数组,来保存我们所有的税率信息。现在我们需要加以处理一番:
functioncalculateTax(stateValue){ var index=0; var result=0; var temp=0; 首先,我们定义一个称为calculateTax的函数。calculateTax会以初始化一些变量开始。然后,它需要从用户那里取得一个值: //while there"s an instance of state //in the taxGuide array while (taxGuide[index]) { //if the state passed in is in the //taxGuide array if (stateValue.toUpperCase() == taxGuide[index].name) { // put the correct tax rate in "result" result = taxGuide[index].tax; } index++; }while 循环会持续将用户的输入,与税率表中的所有可能的条目进行比较,直到比完完全部数据。一旦它发现一个匹配(或是没有匹配),它就将适当的税率写入 result 变量中。然后我们可以使用该税率来计算总量,然后将其加至我们的总额之中。
{ calcTotal(); var temp1 = document.orderForm.totalPrice.value; // calculate total with tax var temp2 = (parseFloat(temp1) * (1 + parseFloat(result))); // chop off extra decimal places vartotalWithTax = (Math.round(temp2 * 100)) / 100; // change value in form document.orderForm.totalPrice.value = totalWithTax; } 上面的代码计算包括税金在内的全部费用。首先,我们设定变量temp1 的值等于totalPrice表单元素的值。然后,我们再计算税后总额,并将其值赋给“temp2”。下一行代码则使用Math.round方法舍去额外的小数位,然后将新的总额赋值给totalWithTax变量。接下来,我们将此总额送回到订购表单之中。来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/8225414/viewspace-957454/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/8225414/viewspace-957454/