六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 28|回复: 0

javascript学习笔录(二)

[复制链接]

升级  19.33%

21

主题

21

主题

21

主题

秀才

Rank: 2

积分
79
 楼主| 发表于 2013-2-3 14:37:51 | 显示全部楼层 |阅读模式
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[loop];}}
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[the_form_number].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[0].elements[0].value = "hello!"; (2)、window.document.forms[the_form_name].elements[the_element_name].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">引用
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表