JavaScript 对象
对象拥有属性和方法。访问对象的属性objectName.propertyName 访问对象的方法objectName.methodName()
创建JavaScript对象(以下几种)
<script> var person=new Object(); person.firstname="John"; person.lastname="Doe"; person.age=50; person.eyecolor="blue"; document.write(person.firstname + " is " + person.age + " years old."); </script>
<script>
person={firstname:"John",lastname:"Doe",age:50,eyecolor:"blue"}
document.write(person.firstname + " is " + person.age + " years old.");
</script> 使用对象构造器 <script>
function person(firstname,lastname,age,eyecolor){
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
}
myFather=new person("John","Doe",50,"blue");
document.write(myFather.firstname + " is " + myFather.age + " years old.");
</script> JavaScript for...in 循环
循环遍历对象的属性<p>点击下面的按钮,循环遍历对象 "person" 的属性。</p>
<button onclick="myFunction()">点击这里</button>
<p id="demo"></p>
<script>
function myFunction(){
var x;
var txt="";
var person={fname:"Bill",lname:"Gates",age:56};
for (x in person){
txt=txt + person[x];
}
document.getElementById("demo").innerHTML=txt;
}
</script> JavaScript prototype(原型对象)
所有的 JavaScript 对象都会从一个 prototype(原型对象)中继承属性和方法。
已存在的对象构造器是不能添加新的属性,必须得从构造器函数中添加。
已存在的对象构造器是不能添加新的属性,必须得从构造器函数中添加。
语法为:构造器函数名.prototype.新属性名=新属性值
<p id="demo"></p>
<script>
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
Person.prototype.nationality = "English"; //对于已经存在的构造器,如果不更改原构造器的同时必须通过prototyoe关键字进行添加
var myFather = new Person("John", "Doe", 50, "blue");
document.getElementById("demo").innerHTML =
"我父亲对国籍是 " + myFather.nationality;
</script> 也可以给对象的构造方法添加新的方法: <p id="demo"></p>
<script>
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
Person.prototype.name = function() {
return this.firstName + " " + this.lastName
};
var myFather = new Person("John", "Doe", 50, "blue");
document.getElementById("demo").innerHTML =
"我对父亲是 " + myFather.name();
</script> JavaScript Number 对象
JavaScript采用IEEE754标准定义的64位浮点格式表示数字,它能表示最大值为±1.7976931348623157 x 10308,最小值为±5 x 10 -324,数字不分为整数类型和浮点型类型如果前缀为 0,则 JavaScript 会把数值常量解释为八进制数,如果前缀为 0 和 "x",则解释为十六进制数。
var myNumber=128; myNumber.toString(16); // 返回 80 转化为16进制 myNumber.toString(8); // 返回 200 转化为8进制 myNumber.toString(2); // 返回 10000000 转化为2进制无穷大(Infinity)
myNumber=2;
while (myNumber!=Infinity)
{
myNumber=myNumber*myNumber; // 重复计算直到 myNumber 等于 Infinity
} 非数字值(NaN) var x = 1000 / "Apple"; isNaN(x); // 返回 true var y = 100 / "1000"; isNaN(y); // 返回 false
ar x = 123; var y = new Number(123); typeof(x) // 返回 Number 数字可以是数字或者对象 typeof(y) // 返回 Object数字也有对象的属性和方法
- MAX_VALUE
- MIN_VALUE
- NEGATIVE_INFINITY
- POSITIVE_INFINITY
- NaN
- prototype
- constructor
- toExponential()
- toFixed()
- toPrecision()
- toString()
- valueOf()
JavaScript 字符串(String) 对象
字符串的索引从零开始, 所以字符串第一字符为 [0],第二个字符为 [1]字符串查找
var str="Hello world, welcome to the universe.";
var n=str.indexOf("welcome"); 内容匹配
var str="Hello world!";
document.write(str.match("world") + "<br>");
document.write(str.match("World") + "<br>");
document.write(str.match("world!")); 替换内容
str="Please visit Microsoft!"
var n=str.replace("Microsoft","Runoob"); 字符串大小写转化 var txt="Hello World!"; // String var txt1=txt.toUpperCase(); // txt1 文本会转换为大写 var txt2=txt.toLowerCase(); // txt2 文本会转换为小写
字符串转换为数组
txt="a,b,c,d,e" // String
txt.split(","); // 使用逗号分隔
txt.split(" "); // 使用空格分隔
txt.split("|"); // 使用竖线分隔 特殊字符 Javascript 中可以使用反斜线(\)插入特殊符号,如:撇号,引号等其他特殊符号
字符串常用的属性和方法:
属性:
- length
- prototype
- constructor
方法:
- charAt()
- charCodeAt()
- concat()
- fromCharCode()
- indexOf()
- lastIndexOf()
- match()
- replace()
- search()
- slice()
- split()
- substr()
- substring()
- toLowerCase()
- toUpperCase()
- valueOf()
JavaScript Date(日期) 对象
创建日期 new Date() // 当前日期和时间
new Date(milliseconds) //返回从 1970 年 1 月 1 日至今的毫秒数
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
new Date(milliseconds) //返回从 1970 年 1 月 1 日至今的毫秒数
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
设置日期
var myDate=new Date();
myDate.setFullYear(2010,0,14);
myDate.setFullYear(2010,0,14);
比较日期
var x=new Date();
x.setFullYear(2100,0,14);
var today = new Date();
if (x>today)
{
alert("今天是2100年1月14日之前");
}
else
{
alert("今天是2100年1月14日之后");
} JavaScript Array(数组) 对象
创建数组
1: 常规方式:
var myCars=new Array();
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";
2: 简洁方式:
var myCars=new Array("Saab","Volvo","BMW");
3: 字面:
var myCars=["Saab","Volvo","BMW"];
访问数组
var name=myCars[0];
JavaScript RegExp 对象
正则表达式
var patt=new RegExp(pattern,modifiers);
或更简单的方法
var patt=/pattern/modifiers;
或更简单的方法
var patt=/pattern/modifiers;
RegExp 修饰符
<script>
var str = "Visit RUnoob";
var patt1 = /runoob/i; //i修饰符是用来执行不区分大小写的匹配 document.write(str.match(patt1));
</script> <script>
var str="Is this all there is?";
var patt1=/is/gi; //g修饰符是用于执行全文的搜索(而不是在找到第一个就停止查找,而是找到所有的匹配) document.write(str.match(patt1));
</script> var patt1=new RegExp("e"); document.write(patt1.test("The best things in life are free")); //true
exec()方法检索字符串中的指定值。返回值是被找到的值。如果没有发现匹配,则返回 null。
var patt1=new RegExp("e"); document.write(patt1.exec("The best things in life are free")); //e
window.document.getElementById("header"); 等同于 document.getElementById("header");
exec()方法检索字符串中的指定值。返回值是被找到的值。如果没有发现匹配,则返回 null。
var patt1=new RegExp("e"); document.write(patt1.exec("The best things in life are free")); //e
JavaScript Window - 浏览器对象模型
浏览器对象模型 (BOM) 使 JavaScript 有能力与浏览器"对话"。window.document.getElementById("header"); 等同于 document.getElementById("header");
一些Window方法:
- window.open() - 打开新窗口
- window.close() - 关闭当前窗口
- window.moveTo() - 移动当前窗口
- window.resizeTo() - 调整当前窗口的尺寸
Window Screen
其中window前缀可以省略- screen.availWidth - 可用的屏幕宽度
- screen.availHeight - 可用的屏幕高度
<script>
document.write("可用宽度: " + screen.availWidth); //可用宽度
</script> Window Location
- location.hostname 返回 web 主机的域名
- location.pathname 返回当前页面的路径和文件名
- location.port 返回 web 主机的端口 (80 或 443)
- location.protocol 返回所使用的 web 协议(http: 或 https:)
<script> document.write(location.href); //返回(当前页面)的URL </script>
<script> document.write(location.pathname); //返回当前URL的路径名 </script>通过点击事件加载指定URL页面文档
<script>
function newDoc(){
window.location.assign("https://www.runoob.com")
}
</script>
</head>
<body>
<input type="button" value="加载新文档" onclick="newDoc()"> Window History
- history.back() - 与在浏览器点击后退按钮相同
- history.forward() - 与在浏览器中点击向前按钮相同
<script>
function goBack()
{
window.history.back()
}
</script>
</head>
<body>
<input type="button" value="Back" onclick="goBack()"> <script>
function goForward()
{
window.history.forward()
}
</script>
</head>
<body>
<input type="button" value="Forward" onclick="goForward()">
Window Navigator
<div id="example"></div>
<script>
txt = "<p>浏览器代号: " + navigator.appCodeName + "</p>";
txt+= "<p>浏览器名称: " + navigator.appName + "</p>";
txt+= "<p>浏览器版本: " + navigator.appVersion + "</p>";
txt+= "<p>启用Cookies: " + navigator.cookieEnabled + "</p>";
txt+= "<p>硬件平台: " + navigator.platform + "</p>";
txt+= "<p>用户***: " + navigator.userAgent + "</p>";
txt+= "<p>用户***语言: " + navigator.systemLanguage + "</p>";
document.getElementById("example").innerHTML=txt;
</script> JavaScript 弹窗
警告框常用于确保用户可以得到某些信息,当警告框出现后,用户需要点击确定按钮才能继续进行操作。<script>
function myFunction()
{
alert("你好,我是一个警告框!");
}
</script>
</head>
<body>
<input type="button" onclick="myFunction()" value="显示警告框"> 确认框验证是否接受用户操作,当确认卡弹出时,用户可以点击 "确认"(返回true) 或者 "取消"(返回false)来确定用户操作。
<button onclick="myFunction()">点我</button>
<p id="demo"></p>
<script>
function myFunction(){
var x;
var r=confirm("按下按钮!");
if (r==true){
x="你按下了\"确定\"按钮!";
}
else{
x="你按下了\"取消\"按钮!";
}
document.getElementById("demo").innerHTML=x;
}
</script> 提示框提示用户在进入页面前输入某个值,当提示框出现后,用户需要输入某个值,然后点击确认或取消按钮才能继续操纵,如果用户点击确认,那么返回值为输入的值。如果用户点击取消,那么返回值为 null。
<p>点击按钮查看输入的对话框。</p>
<button onclick="myFunction()">点我</button>
<p id="demo"></p>
<script>
function myFunction(){
var x;
var person=prompt("请输入你的名字","Harry Potter");
if (person!=null && person!=""){
x="你好 " + person + "! 今天感觉如何?";
document.getElementById("demo").innerHTML=x;
}
}
</script> JavaScript 计时事件
一个设定的时间间隔之后来执行代码称之为计时事件。- setInterval() - 间隔指定的毫秒数不停地执行指定的代码。window.setInterval("javascript function",milliseconds);
- setTimeout() - 在指定的毫秒数后执行指定代码。
<p>单击按钮每3秒出现一个“Hello”警告框。</p>
<p>再次点击警告框,经过3秒出现新的警告框,这将一直执行 ...</p>
<button onclick="myFunction()">点我</button>
<script>
function myFunction(){
setInterval(function(){alert("Hello")},3000);
}
</script> 每秒设置一次,相当于时钟。 <p>在页面显示一个时钟</p>
<p id="demo"></p>
<script>
var myVar=setInterval(function(){myTimer()},1000);
function myTimer(){
var d=new Date(); //显示当前时间
var t=d.toLocaleTimeString(); //转化为字符串
document.getElementById("demo").innerHTML=t;
}
</script> clearInterval() 方法用于停止 setInterval() 方法执行的函数代码<p>页面上显示时钟:</p>
<p id="demo"></p>
<button onclick="myStopFunction()">停止</button>
<script>
var myVar=setInterval(function(){myTimer()},1000);
function myTimer(){
var d=new Date();
var t=d.toLocaleTimeString();
document.getElementById("demo").innerHTML=t;
}
function myStopFunction(){
clearInterval(myVar); //停止执行时间,参数为设置时间的变量
}
</script> setTimeout() 方法
每隔指定时间执行某个函数<p>点击按钮,在等待 3 秒后弹出 "Hello"。</p>
<button onclick="myFunction()">点我</button>
<script>
function myFunction(){
setTimeout(function(){alert("Hello")},3000);
}
</script>
停止以上事件 <p>点击第一个按钮等待3秒后出现"Hello"弹框。</p>
<p>点击第二个按钮来阻止第一个函数运行。(你必须在3秒之前点击它)。</p>
<button onclick="myFunction()">点我</button>
<button onclick="myStopFunction()">停止弹框</button>
<script>
var myVar;
function myFunction(){
myVar=setTimeout(function(){alert("Hello")},3000);
}
function myStopFunction(){
clearTimeout(myVar);
}
</script> JavaScript Cookie
Cookie 用于存储 web 页面的用户信息。以名/值对的形式存储username=John Doe。创建Cookie
- document.cookie="username=John Doe";
- document.cookie="username=John Doe; expires=Thu, 18 Dec 2043 12:00:00 GMT"; //添加一个过期时间
- document.cookie="username=John Doe; expires=Thu, 18 Dec 2043 12:00:00 GMT; path=/"; //path参数告诉浏览器cookie的路径
读取Cookie document.cookie 将以字符串的方式返回所有的 cookie,类型格式: cookie1=value; cookie2=value;cookie3=value;
- var x = document.cookie;
修改Cookie 类似于创建,新值覆盖旧值。
- document.cookie="username=John Smith; expires=Thu, 18 Dec 2043 12:00:00 GMT; path=/";
删除Cookie 设置 expires 参数为以前的时间即可
- document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 GMT";
设置cookie值的函数
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值的函数 function checkCookie()
{
var username=getCookie("username");
if (username!="")
{
alert("Welcome again " + username);
}
else
{
username = prompt("Please enter your name:","");
if (username!="" && username!=null)
{
setCookie("username",username,365);
}
}
} JavaScript 库
jQuery、Prototype、MooTools引入jQuery <script src="https://cdn.staticfile.org/jquery/1.8.3/jquery.min.js"> </script>
<script src="https://cdn.staticfile.org/jquery/1.8.3/jquery.min.js"> </script>
function myFunction()
{
$("#h01").html("Hello jQuery");
}
$(document).ready(myFunction);
等同于传统的
function myFunction()
{
var obj=document.getElementById("h01");
obj.innerHTML="Hello jQuery";
}
onload=myFunction; 引入Prototype库 <script src="https://cdn.staticfile.org/prototype/1.7.3/prototype.min.js"> </script> ……


京公网安备 11010502036488号