\n'); } function setFlash(){ var myFlshObj = document.myFlash; var photoAlbum=document.getElementById('photoAlbum'); if(photoAlbum&&myFlshObj){ var awidth=0; awidth=parseInt(photoAlbum.offsetWidth); if(awidth<260) myFlshObj.height='150px'; if(awidth>=260 && awidth<350) myFlshObj.height='240px'; if(awidth>=350 && awidth<370) myFlshObj.height='305px'; if(awidth>=370 && awidth<550) myFlshObj.height='320px'; if(awidth>=550 && awidth<730) myFlshObj.height='455px'; if(awidth>=730) myFlshObj.height='590px'; } } function setAlbumUrl(name){ albumTypename=name; setFlash(); myFlash_DoFSCommand(null,"test"); } function showLoginWindow(ev){ var obj = document.getElementById("pop-login"); if(document.all){ obj.style.top = ev.clientY +'px'; obj.style.left = ev.clientX - 272 +'px'; } else{ obj.style.top = ev.pageY +'px'; obj.style.left = ev.pageX - 272 +'px' } obj.style.display ="block"; document.getElementById("pop-user-name").focus(); } function hideLoginWindow(){ document.getElementById("pop-login").style.display ="none"; } var blogID=getBlogID(); var UserName = ""; if(blogID!=null){ var tmpUserName=blogID.split("."); UserName=tmpUserName[0]; } function resize(obj){ if(window.event.srcElement.tagName == 'A'){ return; } obj.parentNode.childNodes[1].style.display = obj.parentNode.childNodes[1].style.display=='none' ? 'block': 'none'; obj.parentNode.childNodes[2].style.display = obj.parentNode.childNodes[2].style.display=='none' ? 'block': 'none'; } function tab(event){ var evt = (document.all)?window.event:event; if(evt.keyCode == 9){ document.getElementById("pop-password").focus(); return false; } else{ return evt.keyCode; } } function tab1(event){ var evt = (document.all)?window.event:event; if(evt.keyCode == 9){ document.getElementById("save").focus(); return false; } else{ return evt.keyCode; } } function tabTrack(event) { var evt = (document.all)?window.event:event; if(evt.keyCode == 9){ document.getElementById("pop-password-track").focus(); return false; } else{ return evt.keyCode; } }
张滨+++++博客
个人资料
最新评论
日志
document.onkeyup=kd()
function ku(){
var oControlRange = document.selection.createRange();
if (oControlRange(0).tagName.toUpperCase() == "IMG") {
alert("您在图片上按了键!")
}
}
</script>
B.19 location对象
它为document对象的一个属性,该文档的完整URL,请不要把它与window.location属性相混淆,后者可用来加载一个新文档,并且window.location属性本身并不是一个对象,同时,window.location可以用脚本修改,而document.location则不能。
属性
hash 以散列号(#)开始的一个字符串,用于指定URL内的一个锚点
host 包括冒号和端口号的URL的主机名部分
hostname 与host属性相同,除了不包括冒号和端口号之外
href 完整的URL
pathname URL的目录路径部分
port URL的:端口部分
protocol URL的类型(http:、ftp:、gopher:等等)
search 以问号(?)开始的URL中的一部分,用于指定搜索信息
target 用户单击链接(TARGET特性)时,用于显示被引用文档的内容的窗口
B.20 math对象
该对象不是其它对象的一个属性,而是一个内置对象,包含了许多数学常量和函数。
属性
E 欧拉常量,自然对数的底(约等于2.718)
LN2 2的自然对数(约等于0.693)
LN10 10的自然对数(约等于2.302)
LOG2E 以2为底的e的对数(约等于1.442)
LOG10E 以10为底的e的对数(约等于o.434)
PI ∏的值(约等于3.14159)
SQRT1_2 0.5的平方根(即l除以2的平方根,约等于o.707)
SQRT2 2的平方根(约等于1.414)
方法
abs() 返回某数的绝对值(即该数与o的距离,例如,2与一2的绝对值都是2)
acos() 返回某数的反余弦值(以弧度为单位)
asin() 返回某数的反正弦值(以弧度为单位)
atan() 返回某数的反正切值(以弧度为单位)
ceil() 返回与某数相等,或大于该数的最小整数(ceil(-22.22)返回-22;ceil22,22)返回23;ceil(22)返回22)
cos() 返回某数(以弧度为单位)的余弦值
exp() 返回en
floor() 与ceil相反(floor(一22.22)返回一23;floor(22.22)返回22; floor(22)返回22)
10g() 返回某数的自然对数(以e为底)
max() 返回两数间的较大值
min() 返回两数问的较小值
pow() 返回m的n次方(其中,m为底,n为指数)
random() 返回0和1之间的一个伪随机数(该方法仅在Netscape
Navigator的UNIX版本中有效)
round() 返回某数四舍五入之后的整数
sin() 返回某数(以弧度为单位)的正弦值
sqrt() 返回某数的平方根
tan() 返回某数的正切值
B.2l navigator对象
该对象不是其它对象的属性,而是一个内置对象它包含了有关加载文档的浏览器的信息。
属性
appCodeName 浏览器的代码名(例如,Mozilla)
appName 浏览器的名字
appVersion 浏览器的版本号
userAgent 由客户机送到服务器的用户与代理头标文本
方法
javaEnabled JavaScript中当前并没有该方法,但是不久之后将会添加上它将查看浏览器是否为兼容JavaScript的浏览器,如果是,继续查看JavaScript是否处于支持状态。
B.22 options数组
该数组是select对象的一个属性,即选择框中的所有选项(<OPTION>)的一个列表。
属性
defaultSelected 选项列表中的缺省选项
index 选项列表中某选项的索引位置
length 选项列表中的选项数(<OPTIONS>)
name 选项列表的名字(NAME特性)
selected 表示选项列表中某选项<OPTION>是否被选中的一个布尔类型值
selectedIndex 选项列表中已选中的<OPTION>的索引(位置)
text 选项列表中<OPTION>标记后的文本
value 选项列表中的VALUE=特性
B.23 Password 对象
它是document对象的一个属性,一个<INPUT TYPE=”PASSWORD”>标记。
属性
defaultValue password对象的缺省值(VAlUE=特性)
name 对象的名字(NAME=特性)
value 该域具有的当前值最初与VALUE=特性(defauttValue)相同,但是,如果脚本修改了该域中的值,则该值将改变
方法
focus 把焦点从该域移开
blur 把焦点移到该域
select 选择输入区域
B.24 radio对象
它是form对象的一个属性,窗体内的一组单选按钮(选项按钮)(<INPUT TYPE=”RADIO”>)。
属性
checked 复选框或选项按钮(单选按钮)的状态
defaultChecked 复选框或选项按钮(单选按钮)的缺省状态
length 一组单选按钮中的按钮数
name 对象的名字(NAME=特性)
value VALUE=特性
方法
click 模拟鼠标单击按钮
事件处理程序
onclick
B.25 reset 对象
它是form对象的一个属性,复位按钮(<INPUT TYPE=”RESET”>)。
属性
name 对象的名字(NAME=特性)
value VALUE=特性
方法
click 模拟鼠标单击按钮
事件处理程序
onclick
B.26 select对象
它是form对象的一个属性,选择框(<SELECT>)。
属性
length 选项列表中的选项数(<OPTIONS>)
name 选项列表的名字(NAME特性)
options 列表中的选项数
selectedlndex 选项列表中已选中的<OPTION>的索引(位置)
text 选项列表中(OPTION)标记之后的文本
value 选项列表中的VALUE=特性
方法
blur 把焦点从选项列表中移走
focus 把焦点移到选项列表中
事件处理程序
Onblur
onchange
Onfocus
B.27 string对象
它不是另一个对象的属性,而是一个内置对象,即一串字符字符串输入脚本中时必须位于引号内。
属性
length 字符串中的字符个数
方法
anchor() 用来把字符串转换到HTML锚点标记内(<A NAME=>)
big() 把字符串中的文本变成大字体(<BIG>)
blink() 把字符串中的文本变成闪烁字体(<BLINK>)
bold() 把字符串中的文本变成黑字体(<B>)
charAt() 寻找字符串中指定位置的一个字符
fixed() 把字符串中的文本变成固定间距字体(<TT>)
fontcolor() 改变字符串中文本的颜色(<FONT COLOR=>)
fontsize() 把字符串中的文本变成指定大小(<FONTSIZE=>)
indexOf() 用来搜索字符串中的某个特殊字符,并返回该字符的索引位置
italics() 把字符串中的文本变成斜字体(<I>)
lastlndexOf() 与indexof相似,但是向后搜索最后一个出现的字符
link() 用来把字符串转换到HTML链接标记中(<A HREF=>)
small() 把字符串中的文本变成小字体(<SMALL>)
strike() 把字符串中的文本变成划掉字体(<STRIKE>)
sub() 把字符串中的文本变成下标(subscript)字体((SUB>)
substring() 返回字符串里指定位置间的一部分字符串
sup() 把字符串中的文本变成上标(superscript)字体(<SUP>)
toLowerCase() 把字符串中的文本变成小写
toUpperCase() 把字符串中的文本变成大写
B.28 submit对象
它是form对象的一个属性,窗体中的一个提交按钮(<INPUT TYPE=”SUBMIT”>)。
属性
name 对象的名字(NAME=特性)
value VALUE=特性
方法
click 模拟鼠标单击按钮
事件处理程序
Onclick
B.29 text对象
它是form对象的一个属性,宙体中的一个文本域(<INPUT TYPE=”TEXT”>)。
属性
defaultValue text对象的缺省值(VALUE=特性)
name 该对象的名字(NAME=特性)
Value 该域具有的当前值,最初与VALUE=特性(defaultValue)相同但是,如果脚本修改了该域中的值,则该值将改变
方法
blur 把焦点从文本框移开
focus 把焦点移到文本框
select 选择输入区域
事件处理程序
Onblur
Onchange
Onfeus
Onselect
B.30 textarea对象
它是form对象的一个属性,宙体中的一个文本区域(<TEXTAREA>)。
属性
defaultValue textarea对象的缺省值(VALUE=特性)
name 该对象的名字(NAME=特性)
value 该域具有的当前值,最初与VALUE=特性(defaultValue)相同,但是,如果脚本修改了该域中的值,则该值将改变了。
方法
blur 把焦点从文本区移开
focus 把焦点移到文本区
select 选择输入区域事件处理程序
Onblur
Onchange
Onfocus
Onselect
B.31 window对象
它是一个顶层对象,而不是另一个对象的属性即浏览器的窗口。
属性
defaultStatus 缺省的状态条消息
document 当前显示的文档(该属性本身也是一个对象)
frame 窗口里的一个框架((FRAME>)(该属性本身也是一个对象)
frames array 列举窗口的框架对象的数组,按照这些对象在文档中出现的顺序列出(该属性本身也是一个对象)
history 窗口的历史列表(该属性本身也是一个对象)
length 窗口内的框架数
location 窗口所显示文档的完整(绝对)URL(该属性本身也是一个对象)不要把它与如document.location混淆,后者是当前显示文档的URL。用户可以改变window.location(用另一个文档取代当前文档),但却不能改变document.location(因为这是当前显示文档的位置)
name 窗口打开时,赋予该窗口的名字
opener 代表使用window.open打开当前窗口的脚本所在的窗口(这是Netscape Navigator 3.0beta 3所引入的一个新属性)
parent 包含当前框架的窗口的同义词。frame和window对象的一个属性
self 当前窗口或框架的同义词
status 状态条中的消息
top 包含当前框架的最顶层浏览器窗口的同义词
window 当前窗口或框架的同义词,与self相同
方法
alert() 打开一个Alert消息框
clearTimeout() 用来终止setTimeout方法的工作
close() 关闭窗口
confirm() 打开一个Confirm消息框,用户可以选择OK或Cancel,如果用户单击OK,该方法返回true,单击Cancel返回false
blur() 把焦点从指定窗口移开(这是Netscape Navigator 3.0 beta 3引入的新方法)
focus() 把指定的窗口带到前台(另一个新方法)
open() 打开一个新窗口
prompt() 打开一个Prompt对话框,用户可向该框键入文本,并把键入的文本返回到脚本
setTimeout() 等待一段指定的毫秒数时间,然后运行指令事件处理程序
OnloadOnunload
用JS显示文字的例子:
<html>
<body>
<script type="text/javascript">
document.write("Hello World!")
</script>
</body>
</html>
用HTML标签来格式化文本的例子:
<html>
<body>
<script type="text/javascript">
document.write("<h1>Hello World!</h1>")
</script>
</body>
</html>
书写JS位置的例子:
打开页面弹出窗口的例子
<html>
<head>
<script type="text/javascript">
function message()
{
alert("网页教学网欢迎你的光临")
}
</script>
</head>
<body "message()">
</body>
</html>
在BODY区内输出显示文本的例子:
<html>
<head>
</head>
<body>
<script type="text/javascript">
document.write("欢迎光临网页教学网http://www.webjx.com")
</script>
</body>
</html>
调用其它的一个JS文件的例子:
<html>
<head>
</head>
<body>
<script src="xxx.js">
</script>
<p>
The actual script is in an external script file called "xxx.js".
</p>
</body>
</html>
变量的使用
变量使用的例子:
<html>
<body>
<script type="text/javascript">
var name = "Hege"
document.write(name)
document.write("<h1>"+name+"</h1>")
</script>
<p>This example declares a variable, assigns a value to it, and then displays the variable.</p>
<p>Then the variable is displayed one more time, only this time as a heading.</p>
</body>
</html>
函数的例子
函数使用的一个例子:
<html>
<head>
<script type="text/javascript">
function myfunction()
{
alert("HELLO")
}
</script>
</head>
<body>
<form>
<input type="button"
onclick="myfunction()"
value="Call function">
</form>
<p>By pressing the button, a function will be called. The function will alert a message.</p>
</body>
</html>
带一个参数的函数的例子:
<html>
<head>
<script type="text/javascript">
function myfunction(txt)
{
alert(txt)
}
</script>
</head>
<body>
<form>
<input type="button"
onclick="myfunction('Hello')"
value="Call function">
</form>
<p>By pressing the button, a function with an argument will be called. The function will alert
this argument.</p>
</body>
</html>
不同的两个参数调用函数的例子:
<html>
<head>
<script type="text/javascript">
function myfunction(txt)
{
alert(txt)
}
</script>
</head>
<body>
<form>
<input type="button"
onclick="myfunction('Good Morning!')"
value="In the Morning">
<input type="button"
onclick="myfunction('Good Evening!')"
value="In the Evening">
</form>
<p>
When you click on one of the buttons, a function will be called. The function will alert
the argument that is passed to it.
</p>
</body>
</html>
利用函数返回值的例子:
<html>
<head>
<script type="text/javascript">
function myFunction()
{
return ("Hello, have a nice day!")
}
</script>
</head>
<body>
<script type="text/javascript">
document.write(myFunction())
</script>
<p>The script in the body section calls a function.</p>
<p>The function returns a text.</p>
</body>
</html>
带参数的函数返回值的例子:
<html>
<head>
<script type="text/javascript">
function total(numberA,numberB)
{
return numberA + numberB
}
</script>
</head>
<body>
<script type="text/javascript">
document.write(total(2,3))
</script>
<p>The script in the body section calls a function with two arguments, 2 and 3.</p>
<p>The function returns the sum of these two arguments.</p>
</body>
</html>
条件语句的例子
简单条件语句的例子:
<html>
<body>
<script type="text/javascript">
var d = new Date()
var time = d.getHours()
if (time < 10)
{
document.write("<b>Good morning</b>")
}
</script>
<p>
This example demonstrates the If statement.
</p>
<p>
If the time on your browser is less than 10,
you will get a "Good morning" greeting.
</p>
</body>
</html>
if ... else 的条件语句的例子:
<html>
<body>
<script type="text/javascript">
var d = new Date()
var time = d.getHours()
if (time < 10)
{
document.write("<b>Good morning</b>")
}
else
{
document.write("<b>Good day</b>")
}
</script>
<p>
This example demonstrates the If...Else statement.
</p>
<p>
If the time on your browser is less than 10,
you will get a "Good morning" greeting.
Otherwise you will get a "Good day" greeting.
</p>
</body>
</html>
用随机数产生连接的例子:
<html>
<body>
<script type="text/javascript">
var r=Math.random()
if (r>0.5)
{
document.write("<a href='http://www.w3schools.com'>Learn Web Development!</a>")
}
else
{
document.write("<a href='http://www.refsnesdata.no'>Visit Refsnes Data!</a>")
}
</script>
</body>
</html>
多条件的语句实现的例子:
<html>
<body>
<script type="text/javascript">
var d = new Date()
theDay=d.getDay()
switch (theDay)
{
case 5:
document.write("Finally Friday")
break
case 6:
document.write("Super Saturday")
break
case 0:
document.write("Sleepy Sunday")
break
default:
document.write("I'm really looking forward to this weekend!")
}
</script>
<p>This example demonstrates the switch statement.</p>
<p>You will receive a different greeting based on what day it is.</p>
<p>Note that Sunday=0, Monday=1, Tuesday=2, etc.</p>
</body>
</html>
循环的例子:
for循环的一个例子:
<html>
<body>
<script type="text/javascript">
for (i = 0; i <= 5; i++)
{
document.write("The number is " + i)
document.write("<br>")
}
</script>
<p>Explanation:</p>
<p>The for loop sets <b>i</b> equal to 0.</p>
<p>As long as <b>i</b> is less than , or equal to, 5, the loop will continue to run.</p>
<p><b>i</b> will increase by 1 each time the loop runs.</p>
</body>
</html>
复杂循环的一个例子:
<html>
<body>
<script type="text/javascript">
for (i = 1; i <= 6; i++)
{
document.write("<h" + i + ">This is header " + i)
document.write("</h" + i + ">")
}
</script>
</body>
</html>
按条件循环while的例子:
<html>
<body>
<script type="text/javascript">
i = 0
while (i <= 5)
{
document.write("The number is " + i)
document.write("<br>")
i++
}
</script>
<p>Explanation:</p>
<p><b>i</b> equal to 0.</p>
<p>While <b>i</b> is less than , or equal to, 5, the loop will continue to run.</p>
<p><b>i</b> will increase by 1 each time the loop runs.</p>
</body>
</html>
do...while循环的例子:
<html>
<body>
<script type="text/javascript">
i = 0
do
{
document.write("The number is " + i)
document.write("<br>")
i++
}
while (i <= 5)
</script>
<p>Explanation:</p>
<p><b>i</b> equal to 0.</p>
<p>The loop will run</p>
<p><b>i</b> will increase by 1 each time the loop runs.</p>
<p>While <b>i</b> is less than , or equal to, 5, the loop will continue to run.</p>
</body>
</html>
字符串对象的例子:
检测字符串长度的例子:
<html>
<body>
<script type="text/javascript">
var str="W3Schools is great!"
document.write("<p>" + str + "</p>")
document.write(str.length)
</script>
</body>
</html>
检测子字符串位置的例子:
<html>
<body>
<script type="text/javascript">
var str="W3Schools is great!"
var pos=str.indexOf("School")
if (pos>=0)
{
document.write("School found at position: ")
document.write(pos + "<br />")
}
else
{
document.write("School not found!")
}
</script>
<p>This example tests if a string contains a specified word. If the word is found it returns the position of the first character of the word in the original string. Note: The first position in the string is 0!</p>
</body>
</html>
检测子字符串是否存在的例子:
<html>
<body>
<script type="text/javascript">
var str = "W3Schools is great!"
document.write(str.match("great"))
</script>
<p>This example tests if a string contains a specified word. If the word is found it returns the word.</p>
</body>
</html>
取子字符串的例子:
<html>
<body>
<script type="text/javascript">
var str="W3Schools is great!"
document.write(str.substr(2,6))
document.write("<br /><br />")
document.write(str.substring(2,6))
</script>
<p>
The substr() method returns a specified part of a string. If you specify (2,6) the returned string will be from the second character (start at 0) and 6 long.
</p>
<p>
The substring() method also returns a specified part of a string. If you specify (2,6) it returns all characters from the second character (start at 0) and up to, but not including, the sixth character.
</p>
</body>
</html>
转换字符串的大小写
<html>
<body>
<script type="text/javascript">
var str=("Hello JavaScripters!")
document.write(str.toLowerCase())
document.write("<br>")
document.write(str.toUpperCase())
</script>
</body>
</html>
数组对象的实例
数组简单应用的例子:
<html>
<body>
<script type="text/javascript">
var famname = new Array(6)
famname[0] = "Jan Egil"
famname[1] = "Tove"
famname[2] = "Hege"
famname[3] = "Stale"
famname[4] = "Kai Jim"
famname[5] = "Borge"
for (i=0; i<6; i++)
{
document.write(famname[i] + "<br>")
}
</script>
</body>
</html>
另一种使用数组的方法:
<html>
<body>
<script type="text/javascript">
var famname = new Array("Jan Egil","Tove","Hege","Stale","Kai Jim","Borge")
for (i=0; i<famname.length; i++)
{
document.write(famname[i] + "<br>")
}
</script>
</body>
</html>
使用数组的一些属性和方法:
<html>
<body>
<script type="text/javascript">
var famname = new Array(3)
famname[0] = "Jani"
famname[1] = "Tove"
famname[2] = "Hege"
document.write(famname.length + "<br>")
document.write(famname.join(".") + "<br>")
document.write(famname.reverse() + "<br>")
document.write(famname.push("Ola","Jon") + "<br>")
document.write(famname.pop() + "<br>")
document.write(famname.shift() + "<br>")
</script>
</body>
</html>
数组的两个方法concat和slice
<html>
<body>
<script type="text/javascript">
var famname = new Array(3)
famname[0] = "Jani"
famname[1] = "Tove"
famname[2] = "Hege"
var famname2 = new Array(3)
famname2[0] = "John"
famname2[1] = "Andy"
famname2[2] = "Wendy"
var famname3 = new Array("Stale","Borge")
document.write(famname.join() + "<br>")
document.write(famname.concat(famname2) + "<br>")
document.write(famname.concat(famname2,famname3) + "<br>")
document.write(famname.slice(1) + "<br>")
</script>
</body>
</html>
日期相关例子:
显示今天的日期:
<html>
<body>
<script type="text/javascript">
var d = new Date()
document.write(d.getDate())
document.write(".")
document.write(d.getMonth() + 1)
document.write(".")
document.write(d.getFullYear())
</script>
</body>
</html>
显示当前的时间:
<html>
<body>
<script type="text/javascript">
var d = new Date()
document.write(d.getHours())
document.write(".")
document.write(d.getMinutes())
document.write(".")
document.write(d.getSeconds())
</script>
</body>
</html>
设置日期:
<html>
<body>
<script type="text/javascript">
var d = new Date()
d.setFullYear("1990")
document.write(d)
</script>
</body>
</html>
UTC时间:
<html>
<body>
<script type="text/javascript">
var d = new Date()
document.write(d.getUTCHours())
document.write(".")
document.write(d.getUTCMinutes())
document.write(".")
document.write(d.getUTCSeconds())
</script>
</body>
</html>
显示当前的星期:
<html>
<body>
<script type="text/javascript">
var d=new Date()
var weekday=new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")
document.write("Today is " + weekday[d.getDay()])
</script>
</body>
</html>
显示当前的日期和星期:
<html>
<body>
<script type="text/javascript">
var d=new Date()
var weekday=new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")
var monthname=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")
document.write(weekday[d.getDay()] + " ")
document.write(d.getDate() + ". ")
document.write(monthname[d.getMonth()] + " ")
document.write(d.getFullYear())
</script>
</body>
</html>
一个走动的时间:
<html>
<head>
<script type="text/javascript">
var timer = null
function stop()
{
clearTimeout(timer)
}
function start()
{
var time = new Date()
var hours = time.getHours()
var minutes = time.getMinutes()
minutes=((minutes < 10) ? "0" : "") + minutes
var seconds = time.getSeconds()
seconds=((seconds < 10) ? "0" : "") + seconds
var clock = hours + ":" + minutes + ":" + seconds
document.forms[0].display.value = clock
timer = setTimeout("start()",1000)
}
</script>
</head>
<body "start()" onunload="stop()">
<form>
<input type="text" name="display" size="20">
</form>
</body>
</html>
数学对象的例子:
<html>
<body>
<script type="text/javascript">
document.write(Math.round(7.25))
</script>
</body>
</html>
产生0-1之间的随机数的例子
<html>
<body>
<script type="text/javascript">
document.write(Math.random())
</script>
</body>
</html>
产生0-10的随机数的例子
<html>
<body>
<script type="text/javascript">
no=Math.random()*10
document.write(Math.round(no))
</script>
</body>
</html>
求最大数的例子:
<html>
<body>
<script type="text/javascript">
document.write(Math.max(2,4))
</script>
</body>
</html>
求最小数的例子:
<html>
<body>
<script type="text/javascript">
document.write(Math.min(2,4))
</script>
</body>
</html>
Convert Celsius to Fahrenheit
<html>
<head>
<script type="text/javascript">
function convert(degree)
{
if (degree=="C")
{
F=document.myform.celsius.value * 9 / 5 + 32
document.myform.fahrenheit.value=Math.round(F)
}
else
{
C=(document.myform.fahrenheit.value -32) * 5 / 9
document.myform.celsius.value=Math.round(C)
}
}
</script>
</head>
<body>
<b>Insert a number in either input field, and the number will be converted into
either Celsius or Fahrenheit.</b>
<br />
<form name="myform">
<input name="celsius" onkeyup="convert('C')"> degrees Celsius<br />
equals<br />
<input name="fahrenheit" onkeyup="convert('F')"> degrees Fahrenheit
</form>
<br />
Note that the <b>Math.round</b> method is used,
so that the result will be returned as a whole number.
</body>
</html>
转变字符为数字的例子
<html>
<head>
<script type="text/javascript">
function toUnicode()
{
var str=document.myForm.myInput.value
if (str!="")
{
unicode=str.charCodeAt(0)
}
document.myForm.unicode.value=unicode
}
</script>
</head>
<body>
<form name="myForm">
Write a character:<br />
<input size="1" name="myInput" maxlength="1" onkeyup="toUnicode()">
<hr />
The character's Unicode:<br />
<input size="3" name="unicode">
</form>
</html>
超级连接对象
用按钮来改变连接位置的例子:
<html>
<head>
<script type="text/javascript">
function myHref()
{
document.getElementById('myAnchor').innerText="Visit W3Schools"
document.getElementById('myAnchor').href="http://www.w3schools.com"
}
</script>
</head>
<body>
<a id="myAnchor" href="http://www.microsoft.com">Visit Microsoft</a>
<form>
<input type="button" onclick="myHref()" value="Change URL and text">
</form>
</body>
</html>
改变连接的打开方式的例子:
<html>
<head>
<script type="text/javascript">
function myTarget()
{
document.getElementById('myAnchor').target="_blank"
}
</script>
</head>
<body>
<a id="myAnchor" href="http://www.w3schools.com">Visit W3Schools</a>
<form>
<input type="button" onclick="myTarget()" value="Make the link open in a new window!">
</form>
<p>Try the link before and after you have pressed the button!</p>
</body>
</html>
使连接获得焦点和失去焦点
<html>
<head>
<style type="text/css">
a:active {color:blue}
</style>
<script type="text/javascript">
function getfocus()
{
document.getElementById('w3s').focus()
}
function losefocus()
{
document.getElementById('w3s').blur()
}
</script>
</head>
<body>
<a id="w3s" href="http://www.w3schools.com">Visit W3Schools.com</a>
<form>
<input type="button" onclick="getfocus()" value="Get Focus">
<input type="button" onclick="losefocus()" value="Lose Focus">
</form>
</body>
</html>
连接打开的方式
<html>
<body>
<script type="text/javascript">
function linkToAnchor(num)
{
var win2=open("tryjs_anchor2.htm","secondLinkWindow","scrollbars=yes,width=250,height=200")
win2.location.hash=num
}
</script>
<h3>Links and Anchors</h3>
<p>Click on a button to display that anchor in window 2!</p>
<form>
<input type="button" value="0" onClick="linkToAnchor(this.value)">
<input type="button" value="1" onClick="linkToAnchor(this.value)">
<input type="button" value="2" onClick="linkToAnchor(this.value)">
<input type="button" value="3" onClick="linkToAnchor(this.value)">
</form>
</body>
</html>
按钮对象
创建一个按钮
<html>
<head>
<script type="text/javascript">
function show_alert()
{
alert("Hello World!")
document.all("myButton").focus()
}
</script>
</head>
<body>
<form>
<input type="button" value="Click me!" name="myButton" onClick="show_alert()" />
</form>
</body>
</html>
显示按钮的名称
<html>
<body>
<form name="myForm">
The form's name is: <input type="text" name="text1" size="20">
<br /><br />
<input type="button" value="Show the form's name" onClick="this.form.text1.value=this.form.name">
</form>
</body>
</html>
显示表单中各个项的名称
<html>
<head>
<script type="text/javascript">
function showFormElements(theForm)
{
str="Form Elements: "
for (i=0; i<theForm.length; i++)
str+=" n " + theForm.elements[i].name
alert(str)
}
</script>
</head>
<body>
<form>
First name: <input type="text" name="fname" size="20">
<br />
Last name: <input type="text" name="lname" size="20">
<br /><br />
<input type="button" name="button1"
value="Display name of form elements"
onClick="showFormElements(this.form)">
</form>
</body>
</html>
副选框的选择和取消
<html>
<head>
<script type="text/javascript">
function check()
{
var x=document.forms.myForm
x[0].checked=true
}
function uncheck()
{
var x=document.forms.myForm
x[0].checked=false
}
</script>
</head>
<body>
<form name="myForm">
<input type="checkbox" value="on">
<input type="button" onclick="check()" value="Check Checkbox">
<input type="button" onclick="uncheck()" value="Uncheck Checkbox">
</form>
</body>
</html>
表单中的副选框的选择与取消
<html>
<head>
<script type="text/javascript">
function check()
{
coffee=document.forms[0].coffee
answer=document.forms[0].answer
txt=""
for (i=0;i<coffee.length;++ i)
{
if (coffee[i].checked)
{
txt=txt + coffee[i].value + " "
}
}
answer.value="You ordered a coffee with " + txt
}
</script>
</head>
<body>
<form>
How would you like your coffee?<br /><br />
<input type="checkbox" name="coffee" value="cream">With cream<br />
<input type="checkbox" name="coffee" value="sugar">With sugar<br />
<br />
<input type="button" name="test" onclick="check()" value="Send order">
<br /><br />
<input type="text" name="answer" size="50">
</form>
</body>
</html>
副选框实现的功能(转换为大写)
<html>
<body>
<script type="text/javascript">
function convertField(field)
{
if (document.form1.convertUpper.checked)
{
field.value=field.value.toUpperCase()
}
}
function convertAllFields()
{
document.form1.fname.value=document.form1.fname.value.toUpperCase()
document.form1.lname.value=document.form1.lname.value.toUpperCase()
}
</script>
<form name="form1">
First name:
<input type="text" name="fname" onChange="convertField(this)" size="20" />
<br />
Last name:
<input type="text" name="lname" onChange="convertField(this)" size="20" />
<br />
Convert fields to upper case
<input type="checkBox" name="convertUpper" onClick="if (this.checked) {convertAllFields()}" value="ON">
</form>
</body>
</html>
文档对象
显示连接的数量
<html>
<body>
<a name="A">First anchor</a><br />
<a name="B">Second anchor</a><br />
<a name="C">Third anchor</a><br />
<br />
Number of anchors in this document:
<script type="text/javascript">
document.write(document.anchors.length)
</script>
</body>
</html>
显示当前所在服务器的地址
<html>
<body>
The domain name for this site is:
<script type="text/javascript">
document.write(document.domain)
</script>
</body>
</html>
显示当前页面的地址:
<html>
<body>
<p>The referrer of a document is the URL of the document that linked to a document.</p>
The referrer of this document is:
<script type="text/javascript">
document.write(document.referrer)
</script>
<p>In this case it is a frame page that is linking to this document. IE returns the URL of the frame page and Netscape returns the URL of the document linking to this document.</p>
</body>
</html>
显示当前文档的标题
<html>
<head>
<title>MY TITLE</title>
</head>
<body>
The title of the document is:
<script type="text/javascript">
document.write(document.title)
</script>
</body>
</html>
用按钮来显示当前页面的地址
<html>
<head>
<script type="text/javascript">
function showURL()
{
alert(document.URL)
}
</script>
</head>
<body>
<form>
<input type="button" onclick="showURL()" value="Show URL">
</form>
</body>
</html>
通过单击可以知道当前的标签
<html>
<head>
<script type="text/javascript">
function getElement()
{
var x=document.getElementById("myHeader")
alert("I am a " + x.tagName + " element")
}
</script>
</head>
<body>
<h1 id="myHeader" onclick="getElement()">Click to see what element I am!</h1>
</body>
</html>
显示表单中元素的个数
<html>
<head>
<script type="text/javascript">
function getElements()
{
var x=document.getElementsByName("myInput")
alert(x.length + " elements!")
}
</script>
</head>
<body>
<form >
<input name="myInput" type="text" size="20"><br />
<input name="myInput" type="text" size="20"><br />
<input name="myInput" type="text" size="20"><br />
<br />
<input name="mybutton" type="button" onclick="getElements()" value="Show how many elements named 'myInput'">
</form>
</body>
</html>
打开一个新的文档,显示几个文字
<html>
<head>
<script type="text/javascript">
function docOpen()
{
document.open()
document.write("<h3>Hello World!</h3>")
}
</script>
</head>
<body>
<form>
<input type="button" onclick="docOpen()" value="Open a new document">
</form>
</body>
</html>
打开一个新的文档,并显示新的文档
<html>
<head>
<script>
function replace()
{
var newDoc=document.open("text/html","replace")
var txt="<html><body>FUN!!!!</body></html>"
newDoc.write(txt)
newDoc.close()
}
</script>
</head>
<body>
<h1>Learning how to access the DOM is....</h1><br />
<Input type ="button" value = "Finish Sentence" onclick="replace()">
</body>
</html>
计算表单的个数
<html>
<body>
<form name="Form1">
Name: <input type="text" size="20">
</form>
<form name="Form2">
Age: <input type="text" size="3">
</form>
<script type="text/javascript">
txt="This document contains: " + document.forms.length + " forms."
document.write(txt)
</script>
</body>
</html>
计算一个页面中图形的个数
<html>
<body>
<img border="0" src="hackanm.gif" width="48" height="48">
<br />
<img border="0" src="compman.gif" width="107" height="98">
<p>
<script type="text/javascript">
document.write("This document contains: " + document.images.length + " images.")
</script>
</p>
</body>
</html>
显示表单的名字
<html>
<body>
<form name="Form1">
Name: <input type="text" size="20">
</form>
<form name="Form2">
Age: <input type="text" size="3">
</form>
<p><b>You can use the form's number:</b></p>
<script type="text/javascript">
document.write("<p>The first form's name is: ")
document.write(document.forms[0].name + "</p>")
document.write("<p>The second form's name is: ")
document.write(document.forms[1].name + "</p>")
</script>
<p><b>Or, the form's name (will not work in Netscape):</b></p>
<script type="text/javascript">
document.write("<p>The first form's name is: ")
document.write(document.forms("Form1").name + "</p>")
document.write("<p>The second form's name is: ")
document.write(document.forms("Form2").name + "</p>")
</script>
</body>
</html>
事件对象
单击弹出窗口
<html>
<head>
<script type="text/javascript">
function whichButton()
{
if (event.button==1)
{
alert("You clicked the left mouse button!")
}
else
{
alert("You clicked the right mouse button!")
}
}
</script>
</head>
<body onmousedown="whichButton()">
<p>Click in the document. An alert box will alert which mouse button you clicked.</p>
</body>
</html>
单击弹出窗口显示鼠标的位置
<html>
<head>
<script type="text/javascript">
function show_coords()
{
x=event.clientX
y=event.clientY
alert("X coords: " + x + ", Y coords: " + y)
}
</script>
</head>
<body onmousedown="show_coords()">
<p>Click in the document. An alert box will alert the x and y coordinates of the cursor.</p>
</body>
</html>
按一个键则显示该键的ASCII码
<html>
<head>
<script type="text/javascript">
function whichButton()
{
alert(event.keyCode)
}
</script>
</head>
<body onkeyup="whichButton()">
<p><b>Note:</b> Make sure the right frame has focus when trying this example!</p>
<p>Press a key on your keyboard. An alert box will alert the unicode of the key pressed.</p>
</body>
</html>
单击任何地方显示鼠标在页面的坐标
<html>
<head>
<script type="text/javascript">
function coordinates()
{
x=event.screenX
y=event.screenY
alert("X=" + x + " Y=" + y)
}
</script>
</head>
<body onmousedown="coordinates()">
<p>
Click somewhere in the document. An alert box will alert the x and y coordinates of the cursor, relative to the screen.
</p>
</body>
</html>
单击之后显示文档的鼠标坐标
<html>
<head>
<script type="text/javascript">
function coordinates()
{
x=event.x
y=event.y
alert("X=" + x + " Y=" + y)
}
</script>
</head>
<body onmousedown="coordinates()">
<p>
Click somewhere in the document. An alert box will alert the x and y coordinates of the cursor.
</p>
</body>
</html>
显示SHIFT是否被按下
<html>
<head>
<script type="text/javascript">
function isKeyPressed()
{
if (event.shiftKey==1)
{
alert("The shift key was pressed!")
}
else
{
alert("The shift key was NOT pressed!")
}
}
</script>
</head>
<body onmousedown="isKeyPressed()">
<p>
Click somewhere in the document. An alert box will tell you if you pressed the shift key or not.
</p>
</body>
</html>
单击显示我们页中的标签
<html>
<head>
<script type="text/javascript">
function whichElement()
{
var tname
tname=event.srcElement.tagName
alert("You clicked on a " + tname + " element.")
}
</script>
</head>
<body onmousedown="whichElement()">
<p>Click somewhere in the document. An alert box will alert the tag name of the element you clicked on.</p>
<h3>This is a header</h3>
<p>This is a paragraph</p>
<img border="0" src="ball16.gif" width="29" height="28" alt="Ball">
</body>
</html>
显示事件发生的类型
<html>
<head>
<script type="text/javascript">
function whichType()
{
alert(event.type)
}
</script>
</head>
<body onmousedown="whichType()">
<p>
Click on the document. An alert box will alert which type of event occurred.
</p>
</body>
</html>
表单对象
用表单显示地址:
<html>
<head>
<script type="text/javascript">
function getAction()
{
var x=document.forms.myForm
alert(x.action)
}
function changeAction()
{
var x=document.forms.myForm
x.action="default.asp"
alert(x.action)
}
</script>
</head>
<body>
<form name="myForm" action="js_examples.asp">
<input type="button" onclick="getAction()" value="View value of action attribute">
<br /><br />
<input type="button" onclick="changeAction()" value="Change value of action attribute">
</form>
</body>
</html>
显示表单所使用的方法
<html>
<head>
<script type="text/javascript">
function formMethod()
{
var x=document.forms.myForm
alert(x.method)
}
</script>
</head>
<body>
<form name="myForm" method="post">
Name: <input type="text" size="20"><br /><br />
<input type="button" onclick="formMethod()" value="Show method">
</form>
</body>
</html>
重置表单
<html>
<head>
<script type="text/javascript">
function formReset()
{
var x=document.forms.myForm
x.reset()
}
</script>
</head>
<body>
<form name="myForm">
<p>Enter some text in the text fields and then press the "Reset form" button</p>
<input type="text" size="20"><br />
<input type="text" size="20"><br />
<br />
<input type="button" onclick="formReset()" value="Reset form">
</form>
</body>
</html>
提交表单
<html>
<head>
<script type="text/javascript">
function formSubmit()
{
document.forms.myForm.submit()
}
</script>
</head>
<body>
<form name="myForm" action="js_form_action.asp" method="get">
Firstname: <input type="text" name="firstname" size="20"><br />
Lastname: <input type="text" name="lastname" size="20"><br /><br />
<input type="button" onclick="formSubmit()" value="Submit">
</form>
</body>
</html>
对email的验证
<html>
<head>
<script type="text/javascript">
function validate()
{
x=document.myForm
at=x.email.value.indexOf("@")
if (at == -1)
{
alert("Not a valid e-mail")
return false
}
}
</script>
</head>
<body>
<form name="myForm" action="tryjs_submitpage.htm" onsubmit="return validate()">
Enter your E-mail:
<input type="text" name="email" size="20">
<input type="submit" value="Submit">
</form>
<p><b>Note:</b> This example ONLY tests if the e-mail address contains an "@" character. A "real-life" code
would have to test for punctuations, spaces and other things as well.</p>
</body>
</html>
输入指定的数才能提交表单
<html>
<head>
<script type="text/javascript">
function validate()
{
x=document.myForm
txt=x.myInput.value
if (txt>=1 && txt<=5)
{
return true
}
else
{
alert("Must be between 1 and 5")
return false
}
}
</script>
</head>
<body>
<form name="myForm" action="tryjs_submitpage.htm" onsubmit="return validate()">
Enter a value from 1 to 5: <input type="text" name="myInput" size="20">
<input type="submit" value="Submit">
</form>
</body>
</html>
输入特定长的字符才能提交表单
<html>
<head>
<script type="text/javascript">
function validate()
{
x=document.myForm
input=x.myInput.value
if (input.length>5)
{
alert("The field cannot contain more than 5 characters!")
return false
}
else
{
return true
}
}
</script>
</head>
<body>
<form name="myForm" action="tryjs_submitpage.htm" onsubmit="return validate()">
Enter some text (you will get a message if you add more than 5 characters):
<input type="text" name="myInput" size="20">
<input type="submit" value="Submit">
</form>
</body>
</html>
对表单的检测
<html>
<head>
<script type="text/javascript">
function validate()
{
x=document.myForm
at=x.email.value.indexOf("@")
code=x.code.value
firstname=x.fname.value
submitOK="True"
if (at==-1)
{
alert("Not a valid e-mail!")
submitOK="False"
}
if (code<1 || code>5)
{
alert("The value must be between 1 and 5")
submitOK="False"
}
if (firstname.length>10)
{
alert("Your name must be less than 10 characters")
submitOK="False"
}
if (submitOK=="False")
{
return false
}
}
</script>
</head>
<body>
<form name="myForm" action="tryjs_submitpage.htm" onsubmit="return validate()">
Enter your e-mail: <input type="text" name="email" size="20"><br />
Enter a value from 1 to 5: <input type="text" name="code" size="20"><br />
Enter your name, max 10 chararcters: <input type="text" name="fname" size="20"><br />
<input type="submit" value="Submit">
</form>
</body>
</html>
设置表单中的一项获得焦点
<html>
<head>
<script type="text/javascript">
function setfocus()
{
document.forms[0].field.focus()
}
</script>
</head>
<body>
<form>
<input type="text" name="field" size="30">
<input type="button" value="Set focus" onclick="setfocus()">
</form>
</body>
</html>
选择文本框中的文本
<html>
<head>
<script type="text/javascript">
function setfocus()
{
document.forms[0].txt.select()
document.forms[0].txt.focus()
}
</script>
</head>
<body>
<form>
<input type="text" name="txt" size="30" value="Hello World!">
<input type="button" value="Select text" onclick="setfocus()">
</form>
</body>
</html>
下拉列表框的取值
<html>
<head>
<script type="text/javascript">
function put()
{
txt=document.forms[0].myList.options[document.forms[0].myList.selectedIndex].text
document.forms[0].favorite.value=txt
}
</script>
</head>
<body>
<form>
Select your favorite browser:
<select name="myList" onchange="put()">
<option>Internet Explorer</option>
<option>Netscape</option>
<option>Opera</option>
</select>
<br /><br />
Your favorite browser is: <input type="text" name="favorite" size="20">
</form>
</body>
</html>
单选按钮的取值
<html>
<head>
<script type="text/javascript">
function check(browser)
{
document.forms[0].answer.value=browser
}
</script>
</head>
<body>
<form>
Select which browser is your favorite:<br /><br />
<input type="radio" name="browser" onclick="check(this.value)" value="Internet Explorer">Internet Explorer<br />
<input type="radio" name="browser" onclick="check(this.value)" value="Netscape">Netscape<br />
<input type="radio" name="browser" onclick="check(this.value)" value="Opera">Opera<br />
<br />
<input type="text" name="answer" size="20">
</form>
</body>
</html>
下拉列表的值的显示
<html>
<head>
<script type="text/javascript">
function put()
{
option=document.forms[0].dropdown.options[document.forms[0].dropdown.selectedIndex].text
txt=document.forms[0].number.value
txt=txt + option
document.forms[0].number.value=txt
}
</script>
</head>
<body>
<form>
Select numbers:<br />
<select name="dropdown">
<option>0</option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
<option>7</option>
<option>8</option>
<option>9</option>
</select>
<input type="button" onclick="put()" value="-->">
<input type="text" name="number" size="20">
</form>
</body>
</html>
下拉列表的连接
<html>
<head>
<script type="text/javascript">
function go(form)
{
location=form.selectmenu.value
}
</script>
</head>
<body>
<form>
<select name="selectmenu" onchange="go(this.form)">
<option>--Select page--</option>
<option value="http://www.microsoft.com">Microsoft</option>
<option value="http://www.altavista.com">AltaVista</option>
<option value="http://www.w3schools.com">W3Schools</option>
</select>
</form>
</body>
</html>
光标自动跳到下一个文本区
<html>
<head>
<script type="text/javascript">
function toUnicode(elmnt,content)
{
if (content.length==elmnt.maxLength)
{
next=elmnt.tabIndex
if (next<document.forms[0].elements.length)
{
document.forms[0].elements[next].focus()
}
}
}
</script>
</head>
<body>
<p>This script automatically jumps to the next input field when the current field's maxlength has been reached.</p>
<form>
<input size="3" tabindex="1" maxlength="3" onkeyup="toUnicode(this,this.value)">
<input size="3" tabindex="2" maxlength="3" onkeyup="toUnicode(this,this.value)">
<input size="3" tabindex="3" maxlength="3" onkeyup="toUnicode(this,this.value)">
</form>
</body>
</html>
Frame, Frameset 和 IFrame 对象
平分两个页面
<html>
<frameset id="myFrameset" cols="50%,50%">
<frame id="leftFrame" src="frame_a_noresize.htm">
<frame id="rightFrame" src="frame_a.htm">
</frameset>
</html>
<html>
<head>
<script type="text/javascript">
function disableResize()
{
parent.document.getElementById("leftFrame").noResize=true
parent.document.getElementById("rightFrame").noResize=true
}
function enableResize()
{
parent.document.getElementById("leftFrame").noResize=false
parent.document.getElementById("rightFrame").noResize=false
}
</script>
</head>
<body bgcolor="#EFE7D6">
<form>
<input type="button" onclick="disableResize()" value="No resize">
<input type="button" onclick="enableResize()" value="Resize">
</form>
<p>Try to resize the frame.</p>
<p>Right-click inside the two frames and select "View Source" to see the source code.</p>
</body>
</html>
是否显示滚动条
<html>
<frameset id="myFrameset" cols="50%,50%">
<frame id="leftFrame" src="frame_a_scrolling.htm">
<frame id="rightFrame" src="frame_a.htm">
</frameset>
</html>
<html>
<head>
<script type="text/javascript">
function enableScrolling()
{
parent.document.getElementById("leftFrame").scrolling="yes"
parent.document.getElementById("rightFrame").scrolling="yes"
}
function disableScrolling()
{
parent.document.getElementById("leftFrame").scrolling="no"
parent.document.getElementById("rightFrame").scrolling="no"
}
</script>
</head>
<body bgcolor="#EFE7D6">
<form>
<input type="button" onclick="enableScrolling()" value="Scroll bars">
<input type="button" onclick="disableScrolling()" value="No scroll bars">
</form>
<p>Right-click inside the frames and select "View Source" to see the source code.</p>
</body>
</html>
改变页面的地址:
<html>
<frameset id="myFrameset" cols="50%,50%">
<frame id="leftFrame" src="frame_a_src.htm">
<frame id="rightFrame" src="frame_a.htm">
</frameset>
</html>
<html>
<head>
<script type="text/javascript">
function newSrc()
{
parent.document.getElementById("leftFrame").src="default.asp"
parent.document.getElementById("rightFrame").src="http://www.w3schools.com"
}
</script>
</head>
<body bgcolor="#EFE7D6">
<form>
<input type="button" onclick="newSrc()" value="Change frame source">
</form>
<p>Right-click inside the two frames and select "View Source" to see the source code.</p>
</body>
</html>
跳出框架
<html>
<head>
<script type="text/javascript">
function breakout()
{
if (window.top!=window.self)
{
window.top.location="tryjs_breakout.htm"
}
}
</script>
</head>
<body>
<form>
Click the button to break out of the frame:
<input type="button" onclick="breakout()" value="Break out!">
</form>
</body>
</html>
更新两个页面
<html>
<frameset rows="25%,*" frameborder="1">
<frame name="upperframe" src="frame_a.htm">
<frame name="lowerframe" src="frames_sourcepage.htm">
</frameset>
</html>
<html>
<head>
<script type="text/javascript">
function changeurl()
{
parent.upperframe.location.href="frame_b.htm"
parent.lowerframe.location.href="frame_c.htm"
}
</script>
</head>
<body>
<form>
<input type="button" onclick="changeurl()" value="Change url">
</form>
<p>Right-click inside the two frames and select "View Source" to see the source code.</p>
</body>
</html>
更新2个以上的页面
<html>
<frameset cols="70%,*" frameborder="1">
<frame src="frames_sourcepage2.htm">
<frameset rows="30%,*" frameborder="1">
<frame name="uframe" src="frame_a.htm">
<frame name="lframe" src="frame_b.htm">
</frameset>
</frameset>
</html>
<html>
<head>
<script type="text/javascript">
function changeurl()
{
parent.uframe.location.href="frame_c.htm"
parent.lframe.location.href="frame_d.htm"
}
</script>
</head>
<body>
<form>
<input type="button" value="Change url" onclick="changeurl()">
</form>
<p>Right-click inside the three frames and select "View Source" to see the source code.</p>
</body>
</html>
更新两个IFRAME
<html>
<head>
<script type="text/javascript">
function twoframes()
{
document.all("frame1").src="frame_c.htm"
document.all("frame2").src="frame_d.htm"
}
</script>
</head>
<body>
<iframe src="frame_a.htm" name="frame1"></iframe>
<iframe src="frame_b.htm" name="frame2"></iframe>
<br />
<form>
<input type="button" onclick="twoframes()" value="Change url of the two iframes">
</form>
</body>
</html>
图象对象
改变图象的高度
<html>
<head>
<script type="text/javascript">
function setHeight()
{
var x=document.images
x[0].height="250"
}
</script>
</head>
<body>
<img src="compman.gif" width="107" height="98" />
<form>
<input type="button" onclick="setHeight()" value="Change height of image">
</form>
</body>
</html>
改变图象
<html>
<head>
<script type="text/javascript">
function setSrc()
{
var x=document.images
x[0].src="hackanm.gif"
}
</script>
</head>
<body>
<img src="compman.gif" width="107" height="98" />
<form>
<input type="button" onclick="setSrc()" value="Change image">
</form>
</body>
</html>
改变图象的宽度
<html>
<head>
<script type="text/javascript">
function setWidth()
{
var x=document.images
x[0].width="300"
}
</script>
</head>
<body>
<img src="compman.gif" width="107" height="98" />
<form>
<input type="button" onclick="setWidth()" value="Change Width">
</form>
</body>
</html>
定位:
显示当前页的地址和改变当前页的地址
<html>
<head>
<script type="text/javascript">
function curr_Location()
{
alert(location)
}
function change_Location()
{
window.location="http://www.w3schools.com"
}
</script>
</head>
<body>
<form>
<input type="button" onclick="curr_Location()" value="Show current URL">
<input type="button" onclick="change_Location()" value="Change URL">
</form>
</body>
</html>
刷新页面
<html>
<head>
<script type="text/javascript">
function refresh()
{
window.location.reload()
}
</script>
</head>
<body>
<form>
<input type="button" value="Refresh page" onclick="refresh()">
</form>
</body>
</html>
导航对象
检测你的浏览器
<html>
<body>
<script type="text/javascript">
document.write("You are browsing this site with: "+ navigator.appName)
</script>
</body>
</html>
显示浏览器更加详细的信息
<html>
<body>
<script type="text/javascript">
document.write("<p>Browser: ")
document.write(navigator.appName + "</p>")
document.write("<p>Browserversion: ")
document.write(navigator.appVersion + "</p>")
document.write("<p>Code: ")
document.write(navigator.appCodeName + "</p>")
document.write("<p>Platform: ")
document.write(navigator.platform + "</p>")
document.write("<p>Cookies enabled: ")
document.write(navigator.cookieEnabled + "</p>")
document.write("<p>Browser's user agent header: ")
document.write(navigator.userAgent + "</p>")
</script>
</body>
</html>
最详细的浏览器的信息
<html>
<body>
<script type="text/javascript">
var x = navigator
document.write("CodeName=" + x.appCodeName)
document.write("<br />")
document.write("MinorVersion=" + x.appMinorVersion)
document.write("<br />")
document.write("Name=" + x.appName)
document.write("<br />")
document.write("Version=" + x.appVersion)
document.write("<br />")
document.write("CookieEnabled=" + x.cookieEnabled)
document.write("<br />")
document.write("CPUClass=" + x.cpuClass)
document.write("<br />")
document.write("OnLine=" + x.onLine)
document.write("<br />")
document.write("Platform=" + x.platform)
document.write("<br />")
document.write("UA=" + x.userAgent)
document.write("<br />")
document.write("BrowserLanguage=" + x.browserLanguage)
document.write("<br />")
document.write("SystemLanguage=" + x.systemLanguage)
document.write("<br />")
document.write("UserLanguage=" + x.userLanguage)
</script>
</body>
</html>
按浏览器不同实现导航
<html>
<head>
<script type="text/javascript">
function redirectme()
{
bname=navigator.appName
if (bname.indexOf("Netscape")!=-1)
{
window.location="tryjs_netscape.htm"
return
}
if (bname.indexOf("Microsoft")!=-1)
{
window.location="tryjs_microsoft.htm"
return
}
window.location="tryjs_other.htm"
}
</script>
</head>
<body "redirectme()">
</body>
</html>
检测浏览器的版本
<html>
<head>
<script type="text/javascript">
function browserversion()
{
txt="Your browser is unknown"
browser=navigator.appVersion
if (browser.indexOf("2.")>-1)
{
txt="Your browser is from the stone-age!"
}
if (browser.indexOf("3.")>-1)
{
txt="You should update your browser!"
}
if (browser.indexOf("4.")>-1)
{
txt="Your browser is good enough!"
}
document.getElementById("message").innerHTML=txt
}
</script>
</head>
<body "browserversion()">
<span id="message"></span>
</body>
</html>
选择对象
设置下拉列表的可用性
<html>
<head>
<script type="text/javascript">
function makeDisable()
{
var x=document.getElementById("mySelect")
x.disabled=true
}
function makeEnable()
{
var x=document.getElementById("mySelect")
x.disabled=false
}
</script>
</head>
<body>
<form>
<select id="mySelect">
<option>Apple</option>
<option>Banana</option>
<option>Orange</option>
</select>
<input type="button" onclick="makeDisable()" value="Disable list">
<input type="button" onclick="makeEnable()" value="Enable list">
</form>
</body>
</html>
返回下拉列表中选择的项的值
<html>
<head>
<script type="text/javascript">
function formAction()
{
var x=document.getElementById("mySelect")
alert(x.length)
}
</script>
</head>
<body>
<form>
<select id="mySelect">
<option>Apple</option>
<option>Banana</option>
<option>Orange</option>
</select>
<input type="button" onclick="formAction()" value="How many options in the list?">
</form>
</body>
</html>
改变下拉列表的大小
<html>
<head>
<script type="text/javascript">
function formAction()
{
var x=document.getElementById("mySelect")
x.size="3"
}
</script>
</head>
<body>
<form>
<select name="mySelect">
<option>Apple</option>
<option>Banana</option>
<option>Orange</option>
<option>Melon</option>
</select>
<input type="button" onclick="formAction()" value="Change size of list">
</form>
</body>
</html>
列表可选择多项
<html>
<head>
<script type="text/javascript">
function formAction()
{
var x=document.getElementById("mySelect")
x.multiple=true
}
</script>
</head>
<body>
<p>
Before you click on the "Select multiple" button, try to select more than one option (by holding down the shift or Ctrl key). Click on the "Select multiple" button and try again.
</p>
<form>
<select name="mySelect" size="3">
<option>Apple</option>
<option>Banana</option>
<option>Orange</option>
</select>
<input type="button" onclick="formAction()" value="Select multiple">
</form>
</body>
</html>
返回所选列表的文本值
<html>
<head>
<script type="text/javascript">
function getText()
{
var x=document.getElementById("mySelect")
alert(x.options[x.selectedIndex].text)
}
</script>
</head>
<body>
<form>
Select your favorite fruit:
<select id="mySelect">
<option>Apple</option>
<option>Orange</option>
<option>Pineapple</option>
<option>Banana</option>
</select>
<br /><br />
<input type="button" onclick="getText()" value="Show text of selected fruit">
</form>
</body>
</html>
删除列表的项目
<html>
<head>
<script type="text/javascript">
function formAction()
{
var x=document.getElementById("mySelect")
x.remove(x.selectedIndex)
}
</script>
</head>
<body>
<form>
<select name="mySelect">
<option>Apple</option>
<option>Banana</option>
<option>Orange</option>
</select>
<input type="button" onclick="formAction()" value="Remove option">
</form>
</body>
</html>
显示屏幕的信息
<html>
<body>
<script type="text/javascript">
document.write("Screen resolution: ")
document.write(screen.width + "*" + screen.height)
document.write("<br />")
document.write("Available view area: ")
document.write(screen.availWidth + "*" + screen.availHeight)
document.write("<br />")
document.write("Color depth: ")
document.write(screen.colorDepth)
document.write("<br />")
</script>
</body>
</html>
表格对象
改变表格的边框
<html>
<head>
<script type="text/javascript">
function changeBorder()
{
document.getElementById('myTable').border="10"
}
</script>
</head>
<body>
<table border="1" id="myTable">
<tr>
<td>100</td>
<td>200</td>
</tr>
<tr>
<td>300</td>
<td>400</td>
</tr>
</table>
<form>
<input type="button" onclick="changeBorder()" value="Change Border">
</form>
</body>
</html>
改变表格的间距
<html>
<head>
<script type="text/javascript">
function padding()
{
document.getElementById('myTable').cellPadding="15"
}
function spacing()
{
document.getElementById('myTable').cellSpacing="15"
}
</script>
</head>
<body>
<table id="myTable" border="1">
<tr>
<td>100</td>
<td>200</td>
</tr>
<tr>
<td>300</td>
<td>400</td>
</tr>
</table>
<form>
<input type="button" onclick="padding()" value="Change Cellpadding">
<input type="button"
设置或获取对象指定的文件名或路径。
<script>
alert(window.location.pathname)
</script>
设置或获取整个 URL 为字符串。
<script>
alert(window.location.href);
</script>
设置或获取与 URL 关联的端口号码。
<script>
alert(window.location.port)
</script>
设置或获取 URL 的协议部分。
<script>
alert(window.location.protocol)
</script>
设置或获取 href 属性中在井号“#”后面的分段。
<script>
alert(window.location.hash)
</script>
设置或获取 location 或 URL 的 hostname 和 port 号码。
<script>
alert(window.location.host)
</script>
设置或获取 href 属性中跟在问号后面的部分。
<script>
alert(window.location.search)
</script>
AJAX指南(2)---- 操作XML
作者:张元一(zhangyuanyi@gmail.com)
日期:2005-12-19
本人才疏学浅,错误和疏漏在所难免,欢迎大家批评指正。
通过上一章的学习,我们已经对AJAX的工作原理有了一个基本的了解,但是上一章的例子中并没有用到AJAX中很重要的一个组件XML,所以上一章的例子最多只能称为AJAH(HTML)或者干脆就是AJAT(TEXT),因此这一章我们就来学习如何使用AJAX操作XML。
同上一章一样,首先我们需要创建一个XMLHttp对象:
var http = getHTTPObject();
假设我们有一个XML文件mailbox.xml,它的内容如下:
<?xml version="1.0" encoding="GB2312"?>
<mailbox>
<mail>
<to>老李</to>
<from>老张</from>
<heading>好久不见!</heading>
<body>好久不见,最近好吗?</body>
</mail>
<mail>
<to>小李</to>
<from>小王</from>
<heading>周末有空么?</heading>
<body>周末有空么?一起看场电影吧!</body>
</mail>
</mailbox>
可以看到,里面存储了两封邮件,现在我们的目标就是把这两封邮件以HTML的方式展现出来,首先我们需要创建一个简单的HTML的界面:
<p><button onclick="loadXMLDoc('bookshelf.xml', parseBookShelf)">查看书架</button></p>
<div id="ajax-sample"></div>
ajax-sample块用于展示邮件,但查看信箱按钮被按下时,loadXMLDoc函数将被调用:
function loadXMLDoc(name, parseFunc)
{
http.open("GET", name, true);
http.onreadystatechange = parseFunc;
http.send(null);
}
可以看到,这个函数只是简单的向服务器发送一个GET请求,真正对XML文档进行处理的是parseFunc,也就是我们传入的parseMailBox函数:
function parseMailBox()
{
//4表示请求已完成
if (http.readyState == 4) {
//responseXML是一个HTML DOM Document对象,
//我们将使用它来解析XML文档
var mailBoxXML = http.responseXML;
//获取所有信件
var mails = mailBoxXML.getElementsByTagName('mail');
var mailStr = "";
for (var i = 0; i < mails.length; i++) {
var mail = mails;
//解析信件
var to = getElementText(mail, "to");
var from = getElementText(mail, "from");
var heading = getElementText(mail, "heading");
var body = getElementText(mail, "body");
//为信件添加附属信息
mailStr += "收信人:" + to + "<br>";
mailStr += "发信人:" + from + "<br>";
mailStr += "标题:" + heading + "<br>";
mailStr += "正文:<br>" + body + "<br><br>";
}
//将信件展示到页面上
document.getElementById("ajax-sample").innerHTML = mailStr;
}
}
getElemenText函数相当简单,它的作用就是获取一个元素的文本:
function getElementText(parentElem, name)
{
var result = parentElem.getElementsByTagName(name)[0];
return result.firstChild.nodeValue;
}
这样一个XML文档就解析完毕了,是不是相当的简单。