基本操作
document.write("<h1>This is a heading</h1>");
<button type="button" onclick="alert('Welcome!')">点击</button>
document.getElementById("demo").innerHTML="Hello JavaScript";
// 改变样式
document.getElementById("demo").style.color="#ff0000";
// 验证输入
if isNaN(x) {alert("Not Numeric")};
// 通常我们在每条可执行的语句结尾添加分号。但是分号是可选的
- Js 注释与java相同
- 运算符与java相同
- 条件语句与java相同
- 循环语句与java 相同
// For/In 循环
var person={fname:"John",lname:"Doe",age:25};
for (x in person){
txt=txt + person[x];
}
- 异常捕获 无法分类型捕获
- === 全等(值和类型)
- 通过var 关键词来声明变量,未赋值的变量值为 undefined, Undefined 这个值表示变量不含有值。
可以通过将变量的值设置为 null 来清空变量。
数据类型
JavaScript 拥有动态类型。这意味着相同的变量可用作不同的类型:
JavaScript 中的所有数字都存储为根为 10 的 64 位(8 比特),浮点数。
所有 JavaScript 数字均为 64 位
// 进制 0开头和8进制, 0x开头为16进制
var y=0377;
var z=0xFF;
// 数组
var cars=new Array();
cars[0]="Audi";
cars[1]="BMW";
var cars=new Array("Audi","BMW","Volvo");
var cars=["Audi","BMW","Volvo"];
// 对象
var person={
firstname : "Bill",
lastname : "Gates",
id : 5566
};
// 取值有两种方式
var name=person.lastname;
var name=person["lastname"];
字符串
var txt="Hello world!"
document.write(txt.length)
document.write(txt.toUpperCase())
document.write(txt.link()) 链接
document.write(txt.bold()) 粗体
document.write(txt.concat()) 连接字符串
document.write(txt.replace()) 正则替换
document.write(txt.search()) 正则查找
document.write(txt.split()) 拆分
数组
var mycars=new Array(2)
mycars[0]="Saab"
mycars[1]="Volvo"
var arr2 = new Array()
arr2[0] = "James"
arr2[1] = "Adrew"
// 合并数组
document.write(arr.concat(arr2))
// 拼接数组 (join==join(,))
document.write(arr.join());
document.write("<br />");
document.write(arr.join("."));
// sort排序
document.write(arr.sort())
函数
function myFunction(argument1,argument2){
return 'xx';
}
变量域
- 局部 函数内的为局部变量
- 全局 函数外的为全局变量
- 把值赋给尚未声明的变量,该变量将被自动变为全局变量。
表单验证
with 方法体中 对对象的调用可以省略
<html>
<head>
<script type="text/javascript">
function validate_email(field,alerttxt)
{
with (field)
{
apos=value.indexOf("@")
dotpos=value.lastIndexOf(".")
if (apos<1||dotpos-apos<2)
{alert(alerttxt);return false}
else {return true}
}
}
function validate_form(thisform)
{
with (thisform)
{
if (validate_email(email,"Not a valid e-mail address!")==false)
{email.focus();return false}
}
}
</script>
</head>
<body>
<form action="submitpage.htm"onsubmit="return validate_form(this);" method="post">
Email: <input type="text" name="email" size="30">
<input type="submit" value="Submit">
</form>
</body>
</html>
DOM
DOM(文档对象模型)
![](https://img.haomeiwen.com/i1633382/5183c1f61361f6ec.gif)
// 查找 id="main" 的元素,然后查找 "main" 中的所有 <p> 元素:
var x=document.getElementById("main");
var y=x.getElementsByTagName("p");
// 改变元素内容
document.getElementById(id).innerHTML=new HTML
// 改变元素属性
document.getElementById("image").src="landscape.jpg";
// 改变样式
document.getElementById("p2").style.color="blue";
// 添加和删除需要知道父元素
// 添加元素
var para=document.createElement("p");
var node=document.createTextNode("这是新段落。");
para.appendChild(node);
// remove 元素
var parent=document.getElementById("div1");
var child=document.getElementById("p1");
parent.removeChild(child);
DOM事件
- onclick
- onload 加载完成
- onUnload 离开页面后(加载新的页面)
- onbeforeunload 离开之前(准备加载)
- onchange 元素内容改变
- onmouseover 鼠标移入
- onmouseout 鼠标移出
- onmousedown 按下
- onmouseup 抬起
- onfocus 获取焦点
对象
JavaScript 是面向对象的语言,但 JavaScript 不使用类。
在 JavaScript 中,不会创建类,也不会通过类来创建对象
创建新对象有两种不同的方法:
- 定义并创建对象的实例
- 使用函数来定义对象,然后创建新的对象实例
// obj
person=new Object();
person.firstname="Bill";
person.lastname="Gates";
person.age=56;
person.eyecolor="blue";
// 简单实用
person={firstname:"John",lastname:"Doe",age:50,eyecolor:"blue"};
// 声明函数
function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
function changeName(name)
{
this.lastname=name;
}
}
var myMother=new person("Steve","Jobs",48,"green");
JavaScript for...in 语句循环遍历对象的属性。
for (对象中的变量)
{
要执行的代码
}
// e.g.
var person={fname:"Bill",lname:"Gates",age:56};
for (x in person)
{
txt=txt + person[x];
}
内建对象
BOM浏览器对象模型
Window对象
所有 JavaScript 全局对象、函数以及变量均自动成为 window 对象的成员。
全局变量是 window 对象的属性。
全局函数是 window 对象的方法。
甚至 HTML DOM 的 document 也是 window 对象的属性之一:
window.innerHeight - 浏览器窗口的内部高度
window.innerWidth - 浏览器窗口的内部宽度
window.open() - 打开新窗口
window.close() - 关闭当前窗口
window.moveTo() - 移动当前窗口
window.resizeTo() - 调整当前窗口的尺寸
Screen
screen.availWidth - 可用的屏幕宽度
screen.availHeight - 可用的屏幕高度
以像素计,减去界面特性,比如窗口任务栏。
Location
location.hostname 返回 web 主机的域名
location.pathname 返回当前页面的路径和文件名
location.port 返回 web 主机的端口 (80 或 443)
location.protocol 返回所使用的 web 协议(http:// 或 https://)
加载一个新的文档: window.location.assign("http://www.w3school.com.cn")
History
history.back() - 与在浏览器点击后退按钮相同
history.forward() - 与在浏览器中点击按钮向前相同
Navigator
window.navigator 对象包含有关访问者浏览器的信息。
window.navigator 对象在编写时可不使用 window 这个前缀。
txt = "<p>Browser CodeName: " + navigator.appCodeName + "</p>";
txt+= "<p>Browser Name: " + navigator.appName + "</p>";
txt+= "<p>Browser Version: " + navigator.appVersion + "</p>";
txt+= "<p>Cookies Enabled: " + navigator.cookieEnabled + "</p>";
txt+= "<p>Platform: " + navigator.platform + "</p>";
txt+= "<p>User-agent header: " + navigator.userAgent + "</p>";
txt+= "<p>User-agent language: " + navigator.systemLanguage + "</p>";
document.getElementById("example").innerHTML=txt;
来自 navigator 对象的信息具有误导性,不应该被用于检测浏览器版本,这是因为:
navigator 数据可被浏览器使用者更改
浏览器无法报告晚于浏览器发布的新操作系统
由于 navigator 可误导浏览器检测,使用对象检测可用来嗅探不同的浏览器。
由于不同的浏览器支持不同的对象,您可以使用对象来检测浏览器。例如,由于只有 Opera 支持属性 "window.opera",您可以据此识别出 Opera。
常用方法
- Math.round 四舍五入
- Math.random 0到1 随机
- Math.PI
- Math.floor(Math.random()*11) 生成0..10的随机数
正则表达式
RegExp 为正则表达对象
RegExp 对象有 3 个方法:test()、exec() 以及 compile()。
var patt1=new RegExp("e");
document.write(patt1.test("The best things in life are free"));
document.write(patt1.exec("The best things in life are free"));
//可以向 RegExp 对象添加第二个参数,以设定检索。例如,如果需要找到所有某个字符的所有存在,则可以使用 "g" 参数 ("global")。
// TODO
消息框
- 警告框 alert("warning")
- 确认框 confirm("文本")
- 提示框 prompt("文本","默认值") 当提示框出现后,用户需要输入某个值,然后点击确认或取消按钮才能继续操纵。
计时
var t=setTimeout("javascript语句",毫秒);
clearTimeout(t);
cookie
document.cookie 将以字符串的方式返回所有的 cookies,类型格式: cookie1=value; cookie2=value; cookie3=value;
如果您设置了新的 cookie,旧的 cookie 不会被覆盖。 新 cookie 将添加到 document.cookie 中,所以如果您重新读取document.cookie,您将获得如下所示的数据:
查找一个指定 cookie 值,您必须创建一个JavaScript 函数在 cookie 字符串中查找 cookie 值。
修改 cookie
document.cookie="
username=John Doe;
expires=Thu, 18 Dec 2013 12:00:00 GMT;
path=/";
// cookie set fun
function setCookie(cname,cvalue,exdays)
{
var d = new Date();
d.setTime(d.getTime()+(exdays*24*60*60*1000));
var expires = "expires="+d.toGMTString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
// cookie 获取
function getCookie(cname)
{
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++)
{
var c = ca[i].trim();
if (c.indexOf(name)==0) return c.substring(name.length,c.length);
}
return "";
}
路径
只有与创建cookie的页面在同一个目录或子目录下的网页才可以访问
在”http://www.cnblogs.com/Darren_code/"这个页面创建一个cookie,那么在"/Darren_code/"这个路径下的页面如:"http://www.cnblogs.com/Darren_code/archive/2011/11/07/Cookie.html"这个页面默认就能取到cookie信息。
域
如”www.qq.com”与”sports.qq.com”公用一个关联的域名”qq.com”,我们如果想让 “sports.qq.com”下的cookie被 “www.qq.com” 访问,我们就需要用到cookie的domain属性,并且需要把path属性设置为 “/“。
document.cookie = "username=Darren;path=/;domain=qq.com"
编码
在输入cookie信息时不能包含空格,分号,逗号等特殊符号,而在一般情况下,cookie信息的存储都是采用未编码的方式。所以,在设置cookie信息以前要先使用escape()函数将cookie值信息进行编码,在获取到 cookie值得时候再使用unescape()函数把值进行转换回来。如设置cookie时:
document.cookie = name + "=" + escape (value);
return unescape(document.cookie.substring(c_start,c_end));
网友评论