lighter 发表于 2013-2-3 14:37:51

javascript学习笔录(二)

1、预装图象
function doPreload(){var the_images = new Array('kwmatt.jpg','matbon.jpg','lunchMat.jpg');preloadImages(the_images);}function preloadImages(the_images_array) {for(loop = 0; loop < the_images_array.length; loop++){   var an_image = new Image();an_image.src = the_images_array;}}
doPreload()函数创建了需要预装的图象名的数组,并把数组作为参数传送到preloadImages()函数, preloadImages()函数包
含了一个循环,每次循环都创建一个新的图象对象,并把图象名设到它的src属性中。

2、创建一个Javascript对象
(1)、最常见的方法
比如,创建一个宠物
function Pet(the_pet_name, the_form_number){this.age = 0;this.hunger = Math.random() * 5;// random number between 0 and 4.99this.health = Math.random() * 5 + 1 ;// random number between 1 and 3.99this.happiness = Math.random() * 5;this.pet_name = the_pet_name;this.form_number = the_form_number;window.document.forms.pet_name.value = the_pet_name;}

这个构造函数有两个参数:宠物名字和要显示其信息的表单号。要创建两个宠物,我们这么做: var pet1 = new Pet("barney",0);var pet2 = new Pet("betty",1);

(2).工厂方式
   function createobject(){      var o=new Object();      o.a=1;      o.b="w";      o.c=function(){};      return o;}
当然,你可以给这个函数传入参数进行定制,但是对函数的创建就重复了。
它还有个相近的版本,但是这个版本可以用new来创建
function createobject(){      this.a=1;      this.b="w";      this.c=function(){};}
(3).使用对象的prototype属性,用一个空构造函数来设置对象名,然后所有的属性和方法都直接用prototype来赋予
function o(){};o.prototype.a=1;o.prototype.b=function(){};
此方法也是用new来创建新对象的。
   
(4).JSON方式来创建
    var o={    a:1,    b:"aa"    c:function(){}}

3、eval()函数,这个函数可以把一个字符串当作一个JavaScript表达式一样去执行它。
通过eval()函数,可以获取难以索引的对象,代码如下:
function simpleSwap(){var the_image = prompt("change parrot or cheese","");var the_image_name = "window.document." + the_image;var the_image_object = eval(the_image_name);the_image_object.src = "ant.gif";}

4、四种手段来设置文本框的文本的简单例子:
如果在一个表单里有一个文本框,象这样:
<form name="the_form"><input type="text" name="the_text_box"></form>

JS代码如下所示:
我们可以用四种手段来设置文本框的文本,代码如下:
var the_form_name = "the_form";var the_element_name = "the_text_box";(1)、window.document.forms.elements.value = "hello!"; (2)、window.document.forms.elements.value = "hello!"; (3)、window.document.the_form.the_text_box.value = "hello!"; (4)、var the_element_string = "window.document." + the_form_name + "." + the_element_name;      var the_element = eval(the_element_string);   the_element_string.value = "hello!";

5、常看的JS错误:
<div class="quote_title">引用
页: [1]
查看完整版本: javascript学习笔录(二)