JavaScript简介参考书,JavaScript the Definitive Guide 4th ed,by
David Flanagan (O'Reilly)
The "Rhino" book
参考网址,//www.devguru.com/(查函数和对象)
入门,http://blog.iyi.cn/tech/javascript/refix.htm
JavaScript
Invented by Netscape Communications
Cross Platform,Object-based,Scripting
Language
解释型语言,其通用核心已嵌入 IE、
NetScape和其他浏览器中。
现在的标准,ECMAScript (ECMA-262)
JavaScript
Client runs
JavaScript
HTTP Request
HTTP Response
HTML file with
embedded JavaScript
JavaScript
All Client Side
动态脚本语言
Can
Adjust HTML
Open Windows,Resize Windows
Animations,Play Sounds
Cannot
Access File System
出于安全考虑,不能对文件进行读写
Do Networking
只能引发浏览器下载某个 URL的文档
JavaScript
Advantages
Better User Experience
(2X Latency)
Disadvantages
Thicker Client
Possible Abuse
JavaScript Basics
嵌入网页的方式:
<script> section in HTML runs on document
load
写成一个文件(,js),然后用下列方式引入:
<script src=url language=“javascript”></script>
No type declarations
undefined if not given a value
Global variables by default
var makes them local
JavaScript核心与其他语言比较
句法构成类似 C,C++和 Java
支持 IF,WHILE语句
支持 &&等运算符
无类型
变量无需明确的类型
对象类似 Perl语言中的关联数组
支持正则表达式和以数组处理的特性
Generate Dynamic HTML
...
<BODY>
...Regular HTML Here....
<SCRIPT TYPE="text/javascript">
<!--
BUILD HTML HERE!!!
//-->
</SCRIPT>
...More Regular HTML....
</BODY>
JavaScript and Browser
JavaScript可以控制浏览器的行为和动作,
常与 DOM结合使用:
document – HTML document
document.name – named element in document
document.images – array of images
document.forms – array of forms
Ways to access window,cookies,etc.
常使用 document,write方法控制浏览器显示内容。
使用事件驱动方式来控制浏览器的行为。
例一,document.write(“String”)
<HTML>
<HEAD><TITLE>Hello!</TITLE></HEAD>
<BODY>
<H1> First JavaScript Page </H1>
<SCRIPT TYPE="text/javascript">
<!--
document.write("<HR/>");
document.write("Hello WWW!");
document.write("<HR/>");
//-->
</SCRIPT>
</BODY>
</HTML>
document.write(“String”)
例二,document.write(“String”)
<HTML>
<HEAD><TITLE>Hello!</TITLE>
<SCRIPT TYPE="text/javascript">
<!--
function referringPage() {
if (document.referrer.length == 0) {
return("<I>none</I>");
} else {
return(document.referrer);
}
}
//-->
</SCRIPT>
</HEAD>
<BODY>
<H1> Extracting Info! </H1>
<SCRIPT TYPE="text/javascript">
<!--
document.writeln("<UL>");
document.writeln("<LI>"
+ document.location);
document.writeln("<LI>“
+ referringPage());
document.writeln("<LI>"
+ navigator.appName);
document.writeln("</UL>");
//-->
</SCRIPT>
</BODY>
</HTML>
document.write(“String”)
Monitor User Events
<input type="button" value="Don't Click
Me!" onClick="dontClick()"/>
function dontClick() {
alert("I told ya not to click!");
}
Monitor User Events
www.devguru.com
DOM
JavaScript is Object-Oriented
JavaScript Interacts with Document Object
Model of Browser
DOM Not Totally Standardized
Objects
http://www.devguru.com
Arrays or Objects?
The Same!
a.foo <=> a["foo"] <=> a[x]
a[2] cannot be accessed as a.2
Global Functions
escape(string)
返回以 ISO-Latin-1 字符集书写的参数的十六进制编码 ;
示例 1,下面的例子返回 "%26",escape("&")
unescape(string)
返回指定值的 ASCII 字符串。
例,unescape("%26"),返回,&”:
Safe Strings
ABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz
1234567890
@ * - _ +,/
Unsafe Strings => %20,%5c,etc...
Communicating with User
Alert window.alert("Hello!");
Confirm window.confirm("Delete files? =D")
Status Bar window.status = "Hi!";
<html>
<head>
<title>JS Demo</title>
<script language="JavaScript">
function hello(greeting) {
var str = greeting + "!!!";
alert(str);
}
count = 0;
function upCount() {
count++;
alert(count);
}
function noFear() {
var fear = document.affirm.fear.value;
if (!document.affirm.mockMode.checked) {
alert("No " + fear + " to be seen around here!");
}
else {
var mock = "Being afraid of " + fear + " is stupid!";
window.status = mock
document.affirm.mock.value = mock;
}
}
</script>
</head>
<body>
<p>
<button onClick="hello('hi there');" >Say
Hello</button>
<br><button onClick="upCount();" >Count</button>
<br><a onClick="alert('holy ####!')">oops</a>
<p>
Thing you are afraid of..,
<form name=affirm>
<input type=text name=fear>
<p><input type=button onClick="noFear();" value="No
Fear">
Mock mode:<input type=checkbox name=mockMode>
<p><input type=text size=40 name=mock>
</form>
</body>
</html>
Fear Example
Quotes Example
Text Box
<form name=form1
onsubmit="setQuotes('form1'); return false;">
Search,<input type=text name=target >
<input type=submit value=Submit>
</form>
Text Box
<input type=text name=target
onKeyUp="setQuotes('form2');">
<script language="JavaScript">
// We allocate a global array and fill it with the quote data.
lines = new Array();
lines.push("Everybody's always telling me one thing and out the
other.");
lines.push("Even a fish could stay out of trouble if it would
just learn to keep its mouth shut.");
lines.push("Beware the lollipop of mediocrity -- lick it once
and you suck forever.");
lines.push("We don't have time to stop for gas -- we're already
late.");
lines.push("By doing just a little each day,I can gradually
let the task overwhelm me.");
lines.push("Being powerful is like being a lady,If you have to
tell people you are,you aren't.");
lines.push("Never attribute to malice that which can
satisfactorily be explained by incompetence.");
// Search for an element with the given id and set its innerHTML to
// the given text.
function setText(id,text) {
var node = document.getElementById(id);
if (node != null) {
node.innerHTML = text;//
//node.childNodes[0].data = text;
// alternative for some simple tags
}
}
// Given the name of a form,access the target field within that
// form and using its target text,generate the quote list and put
// it into the result tag.
function setQuotes(form_name) {
// cute,use [] instead of,to access the form by name
var target = document[form_name].target.value;
var contents = "";
target = target.toLowerCase();
for (var i in lines) {
if (lines[i].toLowerCase().indexOf(target)!=-1) {
contents = contents + "<li>" + lines[i] + "\n";
}
}
setText("result",contents);
}
</script>
试验方法
编写代码;
对于简单的 JavaScript脚本可以使用
JavaScript,URL伪协议来进行实验。如:在浏览器的 LOCATION输入:
JavaScript,5%2。
JavaScript,d=new Date();d=‘<h1>’+d+’</d1>’
当浏览器装载时,将执行这样的代码,并将结果显示在浏览器中。
例子
匹配 URL( url)
数字时钟( clock)
鼠标跟随的时钟( clockm)
匹配 URL
<HTML>
<HEAD><TITLE> 串的操作 </TITLE></HEAD>
<BODY> <script language="javascript">
var
text1='http://infolab.stanford.edu/~ullman/dragon/w06/w06.html';
var result=text1.match(/(\w+):\/\/([\w+.]+[\w+])\/(\S+)/);
if (result!=null){
document.writeln(result[0],'<hr>');
document.writeln(result[1],'<hr>');
document.writeln(result[2],'<hr>');
document.writeln(result[3],'<hr>'); }
</script>
</BODY>
</HTML>
JavaScript Summary
Good For Simple Things
Save RT Latency
Bad when Abused
Popups!!!
Don't Always Rely on It
DOMs not standardized