JavaScript
一种基于对象(object)和事件驱动(Event Driven)的嵌入式脚本语言。
简单的例子
<html>
<head>
<title>Displaying Time</title>
</head>
<body>
<script language = "JavaScript" type = "text/javascript" >
function time(){
//系统时间
now = new Date(); // new关键字创建对象
/* hours 时
mins 分
secs 秒 */
hours = now.getHours();
mins = now.getMinutes();
secs = now.getSeconds();
document.write(hours + ":" + mins + ":" + secs)
}
</script>
<input type = "button" name = "button" value = "clieck me" onClick = " time();">
</body>
</html>
脚本可位于 HTML 的 <body>
或 <head>
部分中,最好放在<head>
中。
1.变量
- 使用字母、数字、下划线 。
- 区分大小写,建议驼峰命名。
- 弱类型
var name = “name”
2.常用方法
String对象
创建String对象
var testStr = “ This is a string ”; //直接赋值 确定类型
属性与常用方法
length 是String对象的长度属性,String.length的值是一个数字。
方法 | |
---|---|
String.indexOf(subString[, startIndex]) | 返回子字符串第一次出现的字符位置 |
String.substring(start, end ) | 截取字符串,返回的是一个字符串 |
String.toUpperCase( ) | 将字符串内的所有字符转换为大写 |
String.toLowerCase( ) | 将字符串内的所有字符转换为小写 |
String.split( ) | 分割字符串 |
例:
var txt="Hello world!"
document.write(txt.length)
Date 日期对象
var 对象名称=new Date (参数)
var date1=new Date( ) //取得当前的系统时间
var date2=new Date( 2000,1,1)
比较日期的方法if(date1>date2)
getYear( )
getMonth()
getDate( )
getHours( )
getMinutes( )
getSeconds( )
setYear (年份)
setMonth(月份)
setDate(日期)
setMinutes(分钟数)
getTime(毫秒数)
setTime(毫秒数)
例:
var myDate=new Date()
myDate.setDate(myDate.getDate()+5)
window 窗口对象
常用方法
window.open(”URL“,”windowName“,”windowFeature“) 用于打开新窗口
windowFeature为可选属性列表,详见windowFeature参数一览
方法 | |
---|---|
window.close( ) | 用于关闭窗口 |
alert(“ ”) | 弹出对话框 |
window.confirm(“ ”) | 弹出确认框 |
window.prompt(“ ”,” ”) | 弹出输入框 |
windowFeature参数一览
top= | 窗口顶部离开屏幕顶部的像素数 |
left= | 窗口左端离开屏幕左端的像素数 |
width= | 窗口的宽度 |
height= | 窗口的高度 |
menubar= | 窗口有没有菜单,取值yes或no |
toolbar= | 窗口有没有工具条,取值yes或no |
location= | 窗口有没有地址栏,取值yes或no |
directories= | 窗口有没有连接区,取值yes或no |
scrollbars= | 窗口有没有滚动条,取值yes或no |
status= | 窗口有没有状态栏,取值yes或no |
resizable= | 窗口给不给调整大小,取值yes或no |
3.DOM 事件
常用事件 | |
---|---|
Onclick | 当用户点击某个对象时调用的事件 |
onload | 一张页面或一幅图像完成加载 |
Onunload | 用户退出页面 |
Onreset | 重置按钮被点击 |
Onchange | 域的内容被改变 |
例:
<script>
function changetext(id) { id.innerHTML="谢谢!"; }
</script>
<body onload=“init()">
<h1 onclick=“changetext(this)”>请点击该文本</h1> //this代表元素自身
</body>