一、js的简介
1、js是什么
js是可以嵌入到html中,是 基于对象 和 事件驱动 的 脚本语言
特点:
(1)交互性
(2)安全性:js不能访问本地磁盘
(3)跨平台:浏览器中都具备js解析器
2、js能做什么
(1)js能动态的修改(增删)html和css的代码
(2)能动态的校验数据
3、js历史及组成
ECMAScript BOM(浏览器对象模型) DOM(文档对象模型)
4、js被引入的方式
(1)内嵌脚本
<input type="button" value="button" οnclick="alert('xxx')" />
(2)内部脚本
<script type="text/javascript">
alert("xxx");
</script>
(3)外部脚本
首先先创建一个js文件
其次在html中引入
<script type="text/javascript" src="outdoors.js"></script>
js代码放在哪?
放在哪都行 但是在不影响html功能的前提下 越晚加载越好
二、js基本语法
1、变量
(1)弱类型语言,变量类型声明为var
var x = 5;
x = 'javascript';
var y = "hello";
var b = true;
(2)直接写,不需要声明类型
x = 5;
2、原始数据类型 调用typeof方法可获得变量类型
(1)number:数字类型
(2)string:字符串类型
(3)boolean:布尔类型
(4)null:空类型
(5)underfind:未定义
注意:number、boolean、string是伪对象
类型转换:
number\boolean转成string
toString();
string\boolean转成number
parseInt()
parseFloat()
boolean不能转
string可以将数字字符串转换成number 如果“123a3sd5” 转成123
强制转换
Boolean() 强转成布尔
数字强转成布尔 非零就是true 零就是false
字符串强转成布尔 非“”(空字符串)就是true 空字符串“”就是false
Number() 强转成数字
布尔转数字 true转成1 false转成0
字符串转数字 不能强转
3、引用数据类型
java: Object obj = new Object();
js: var obj = new Object();
var num = new Number();
4、运算符
(1)赋值运算符
var x = 5;
(2)算数运算符
+ - * / %
+: 遇到字符串变成连接
-:先把字符串转成数字然后进行运算
*: 先把字符串转成数字然后进行运算
/: 先把字符串转成数字然后进行运算
(3)逻辑运算符
&& ||
(4)比较运算符
< > >= <= != ==
===:全等:类型与值都要相等
(5)三元运算符
3<2?"大于":"小于"
(6)void运算符
<a href="javascript:void(0);">xxxxxx</a>
(7)类型运算符
typeof:判断数据类型 返回我的数据类型
instanceof:判断数据类型 是否是某种类型
var obj = new Object();
alert(typeof obj);//object
alert(obj instanceof Object);//true
5、逻辑语句
(1)if-else
//条件:
//数字非0 字符串非空====true
if(9){
alert("true--");
} else{
alert("false--");
}
(2)switch
var x = "java";
switch(x){
case "css":
alert("css");
break;
case "js":
alert("js");
break;
case "java":
alert("java");
break;
default:
alert("def");
}
(3)for和while 基本和Java一样
for(var i = 0;i<5;i++) {
alert(i);
}
(4)for in
var arr = [1,3,5,7,"js"];
for(index in arr) {//index代表角标
//alert(index);
alert(arr[index]);
}
三、js的内置对象
(1)Number
创建方式:
(2)Boolean
创建方式:
var bool = new Boolean(value);
var bool = Boolean(value);
属性和方法:
toString():转成字符串
valueOf():返回一个 Boolean 对象的基本值(boolean)
(3)String
创建方式:
var str = new String(s);
var str = String(s);
属性和方法:
length:字符串的长度
charAt():返回索引字符
charCodeAt:返回索引字符unicode
indexOf():返回字符的索引
lastIndexOf();逆向返回字符的索引
split();将字符串按照特殊字符切割成数组
substr():从起始索引号提取字符串中指定数目的字符
substring():提取字符串中两个指定的索引号之间的字符
toUpperCase();转大写
(4)Array
创建方式:
var arr = new Array();//空数组
var arr = new Array(size);//创建一个指定长度的数据
var arr = new Array(element0, element1, ..., elementn);//创建数组直接实例化元素
var arr = [];//空数组
var arr = [1,2,5,"java"];//创建数组直接实例化元素
属性和方法:
length:数组长度
join():把数组的所有元素放入一个字符串。元素通过指定的分隔符进行分隔一个
pop():删除并返回最后元素
push():向数组的末尾添加一个或更多元素,并返回新的长度
reverse();反转数组
sort();排序
(5)Date
创建方式:
var myDate = new Date();
var myDate = new Date(毫秒值);//代表从1970-1-1到现在的一个毫秒值
属性和方法
getFullYear():年
getMonth():月 0-11
getDate():日 1-31
getDay():星期 0-6
getTime():返回1970年1月1日午夜到指定日期(字符串)的毫秒数
toLocalString();获得本地时间格式的字符串
(6)Math
创建方式:
Math 对象并不像 Date 和 String 那样是对象的类,因此没有构造函数 Math(),像 Math.sin() 这样的函数只是函数,
不是某个对象的方法。您无需创建它,通过把 Math 作为对象使用就可以调用其所有属性和方法。
属性和方法
PI:圆周率
abs():绝对值
ceil():对数进行上舍入
floor():对数进行下舍入
pow(x,y):返回 x 的 y 次幂
random():0-1之间的随机数
round():四舍五入
(7)RegExp
创建方式:
var reg = new RegExp(pattern);
var reg = /^正则规则$/;
规则的写法:
[0-9] 数字
[A-Z] 大写字母
[a-z] 小写字母
[A-z] 是字母就行
\d 代表数字
\D 非数字
\w 查找单词字符
\W 查找非单词字符
\s 查找空白字符
\S 查找非空白字符
n+ 出现至少一次
n* 出现0次或多次
n? 出现0次或1次
{5} 出现5
{2,8} 2到8次
方法:
test(str):检索字符串中指定的值。返回 true 或 false
需求:
校验邮箱:
var email = haohao_827@163.com
var reg = /^[A-z]+[A-z0-9_-]*\@[A-z0-9]+\.[A-z]+$/;
reg.test(email);
示例 demo1.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
</body>
<script type="text/javascript">
//--------------------Number-----------------------------
//var num = new Number(5);
//alert(typeof num);//object
//alert(typeof num.toString());//string
//alert(typeof num.valueOf());//number
//--------------------String-----------------------------
var str = new String("a-b-cdc-FG");
//alert(str.length);//10
//alert(str.charAt(4));//c
//alert(str.charCodeAt(4));//99
//alert(str.indexOf("c"));//4
//alert(str.lastIndexOf("c"));//6
//var arr = str.split("-");
/* for(var i=0;i<arr.length;i++){
alert(arr[i]);
} */
//alert(str.substr(2,3));//b-c
//alert(str.substring(2,3));//b
//alert(str.toUpperCase());
//--------------------Array-----------------------------
//var arr = [3,"z",1,"java",'js',true,4];
//alert(arr.length);//7
//alert(arr.join("-"));//3-7-1-java-js-true-4
//alert(arr.pop());//4
//alert(arr);//3,7,1,"java",'js',true
//alert(arr.push("R"));
//alert(arr);
//alert(arr.reverse());
//alert(arr.sort());//按照字符串字典顺序进行排序
//--------------------Date-----------------------------
var date = new Date();
//alert(date.toString());
//alert(date.toLocaleString());
/* alert("year:"+date.getFullYear());//2015
alert("month:"+date.getMonth());//8
alert("date:"+date.getDate());//23
alert("day:"+date.getDay());//3 */
/* var time1 = date.getTime();
var time2 = 3*24*60*60*1000;
alert(new Date(time1+time2).toLocaleString()); */
//--------------------Math-----------------------------
/* var x = "-897";
alert(Math.abs(x)); */
/* var x = 12.34;
var y = 2;
var z = 4; */
/* alert(Math.ceil(x));//13
alert(Math.floor(x));//12
alert(Math.round(x));//12 */
//alert(Math.pow(y, z));//16
//alert(Math.random());
//--------------------RegExp-----------------------------
/* var email = "haohao_827@163.com";
var reg = /^[A-z]+[A-z0-9_-]*\@[A-z0-9]+\.[A-z]+$/;
alert(reg.test(email)); */
</script>
</html>
四、js的函数
1、js函数定义的方式
(1)普通方式
语法:function 函数名(参数列表){函数体}
示例:
function method(){
alert("xxx");
}
method();
(2)匿名函数
语法:function(参数列表){函数体}
示例:
var method = function(){
alert("yyy");
};
method();
(3)对象函数(基本不用)
语法:new Function(参数1,参数2,...,函数体);
注意:参数名称必须使用字符串形式、最后一个默认是函数体且函数体需要字符串形式
示例:
var fn = new Function("a","b","alert(a+b)");
fn(2,5);
完整实例:
<html>
<head>
<meta charset="UTF-8">
<title>JS函数定义方式</title>
</head>
<body>
</body>
<script>
// 1.普通方式
function method() {
alert("xxx");
}
//调用
method();
// 2.匿名方法
var method = function() {
alert("yyy");
};
method();
// 3.对象方式
var fn = new Function("a", "b", "alert(a + b)");
fn(2,5)
</script>
</html>
2、函数的参数
(1)形参没有var去修饰
(2)形参和实参个数不一定相等
(3)arguments对象 是个数组 会将传递的实参进行封装
function fn(a,b,c){
//var sum = a+b+c;
//alert(sum);
//arguments是个数组 会将传递的实参进行封装
for(var i=0;i<arguments.length;i++){
alert(arguments[i]);
}
}
fn(1,2,4,8);
3、返回值
(1)在定义函数的时候不必表明是否具有返回值
(2)返回值仅仅通过return关键字就可以了 return后的代码不执行
function fn(a,b){
return a+b;
//alert("xxxx");
}
alert(fn(2,3));
完整实例:
<html>
<head>
<meta charset="UTF-8">
<title>JS函数传参</title>
</head>
<body>
</body>
<script>
// 1.实参少于或者多于形参的情况
function add(a, b, c){
sum = a + b + c;
alert(sum);
for (var index in arguments) {
alert(arguments[index]);
}
}
// 参数少了会弹出"NaN":
//alert(1,2);
// 会弹出"7",执行下面的循环会弹出1,2,4,8:
add(1,2,4,8);
// 2.函数返回值
function fn(a, b){
return a + b;
}
alert(fn(2,3));
</script>
</html>
4、js的全局函数
(1)编码和解码
encodeURI() decodeURI()
encodeURIComponet() decodeURIComponent()
escape() unescape()
三者区别:
进行编码的符号范围不同吧,实际开发中常使用第一种
示例代码:
<html>
<head>
<meta charset="UTF-8">
<title>JS全局函数</title>
</head>
<body>
</body>
<script>
var url = "http://www.baidu.com?name=zhangsan&password=123";
alert(encodeURI(url));
// http://www.baidu.com?name=zhangsan&password=123
alert(encodeURIComponent(url));
// http%3A%2F%2Fwww.baidu.com%3Fname%3Dzhangsan%26password%3D123
alert(escape(url));
// http%3A//www.baidu.com%3Fname%3Dzhangsan%26password%3D123
</script>
</html>
(2)强制转换
Number()
String()
Boolean()
(3)转成数字
parseInt()
parseFloat()
(4)eval()方法
将字符串当作脚本进行解析运行,实现代码注入
//var str = "var a=2;var b=3;alert(a+b)";
//eval(str);
function print(str){
eval(str);
}
print("自定义逻辑");
示例代码:
<html>
<head>
<meta charset="UTF-8">
<title>eval函数用法</title>
</head>
<body>
</body>
<script>
var str = "a = 3; b = 3; alert(a + b)";
eval(str);
</script>
</html>
五、js事件
以点击提交按钮为例
事件 : 点击按钮事件源 : 按钮
响应行为: 提交给服务器
1、js常见事件
onclick : 点击事件
onchange: 域内容被改变事件
实现省级联动(省市级联):
<html>
<head>
<meta charset="UTF-8">
<title>onchange</title>
</head>
<body>
<select id="city">
<option value="bj">北京</option>
<option value="hb">湖北</option>
<option value="zj">浙江</option>
</select>
<select id="area">
<option>海淀</option>
<option>朝阳</option>
<option>东城</option>
</select>
</body>
<script>
var selectcity = document.getElementById("city");
var selectarea = document.getElementById("area");
selectcity.onchange = function() {
var optionVal = selectcity.value;
switch(optionVal) {
case "bj":
selectarea.innerHTML = "<option>海淀</option><option>朝阳</option><option>东城</option>";
break;
case "hb":
selectarea.innerHTML = "<option>武汉</option><option>黄冈</option><option>十堰</option>";
break;
case "zj":
selectarea.innerHTML = "<option>杭州</option><option>温州</option>";
break;
default:
alert("error!");
}
}
</script>
</html>
onfocus : 获得焦点事件
onblur : 失去焦点事件
<html>
<head>
<meta charset="UTF-8">
<title>focus and blur</title>
</head>
<body>
<label for="txt">name</label>
<input id="txt" type="text" /> <span id="action"></span>
</body>
<script>
var txt = document.getElementById("txt");
txt.onfocus = function(){
// 友好提示
var span = document.getElementById("action")
span.innerHTML = "用户名格式最小8位";
span.style.color = "green";
};
txt.onblur = function() {
// 错误提示
var span = document.getElementById("action")
// 补充判断的代码
span.innerHTML = "对不起格式不正确!";
span.style.color = "red";
};
</script>
</html>
onmouseover : 鼠标悬浮事件
onmouseout : 鼠标离开事件
div元素 鼠标移入变为绿色,移出变为原色
<html>
<head>
<meta charset="UTF-8">
<title>onmouseover and out</title>
<style>
#d1{
background-color:red;
height:200px;
width:200px;
}
</style>
</head>
<body>
<div id="d1"></div>
</body>
<script>
var d1 = document.getElementById("d1");
d1.onmouseover = function(){
//alert("xxx");
this.style.backgroundColor="green";
};
d1.onmouseout = function(){
//alert("yyy");
this.style.backgroundColor="red";
};
</script>
</html>
onload : 加载完毕的事件
等到页面加载完毕再执行onload事件所指向的函数
<html>
<head>
<meta charset="UTF-8">
<title>onload</title>
<script type="text/javascript">
// window 表示整个页面对象
window.onload = function() {
var span = document.getElementById("span");
// alert(span);
span.innerHTML = "hello js!";
}
</script>
</head>
<body>
<span id="span"></span>
</body>
</html>
2、事件的绑定方式
(1)将事件和响应行为都内嵌到html标签中
<input type="button" value="button" οnclick="alert('xxx')"/>
(2)将事件内嵌到html中而响应行为用函数进行封装
<input type="button" value="button" οnclick="fn()" />
<script type="text/javascript">
function fn(){
alert("yyy");
}
</script>
(3)将事件和响应行为 与html标签完全分离
<html>
<head>
<meta charset="UTF-8">
<title>js event!</title>
</head>
<body>
<input type="button" value="button" id = "btn" οnclick="alert('xxx')"/>
</body>
<script>
var btn = document.getElementById("btn");
// 为id为btn的对象的单击事件绑定匿名函数
btn.onclick = function() {
alert("xxx");
};
</script>
</html>
****this关键字
this经过事件的函数进行传递的是html标签对象
// 弹出“mybtn”
<input id="btn" name="mybtn" type="button" value="button123" οnclick="fn(this)"/>
<script type="text/javascript">
function fn(obj){
alert(obj.name);
}
</script>
3、阻止事件的默认行为
<html>
<head>
<meta charset="UTF-8">
<title>阻止事件的默认行为</title>
</head>
<body>
<a href="https://www.baidu.com" οnclick="fn(event)">点击我吧</a>
</body>
<script>
function fn(e){
// ie : window.event.returnValue = false;
// W3c(firefox or chrome) :
// W3c标准
if (e && e.preventDefault){
alert("W3c");
e.preventDefault();
} // IE标准
else {
alert("IE标准");
window.event.returnValue = false;
}
}
</script>
</html>
//通过事件返回false也可以阻止事件的默认行为
<a href="demo11.html" οnclick="return false">点击我吧</a>
4、阻止事件的传播
IE:window.event.cancelBubble = true;
W3c: 传递过来的事件对象.stopPropagation();
//IE标准
完整示例代码:
<html>
<head>
<meta charset="UTF-8">
<title>防止事件传播</title>
<script type="text/javascript">
function fn1(){
alert("fn1() called");
}
/*function fn2(){
alert("fn2() called");
}*/
function fn2(e){
alert("fn2() called");
// 阻止事件的传播
if(e&&e.stopPropagation){
alert("w3c");
e.stopPropagation();
} // IE标准
else{
alert("ie");
window.event.cancelBubble = true;
}
}
</script>
</head>
<body>
<div οnclick="fn1()" style="width:100px;heigth:100px;background-color:green;padding:40px">
<!--<div οnclick="fn2()" style="width:100px;height:100px;background-color:red;">xxx</div>-->
<div οnclick="fn2(event)" style="width:100px;height:100px;background-color:red;">xxx</div>
</div>
</body>
</html>
六、js的bom
1、window对象
弹框的方法
提示框 : alert("提示信息");没有返回值,强行返回undefined
确认框 : confirm("确认信息");有返回值——点击确认返回true,取消返回false;
输入框 : prompt("提示信息");有返回值——点击确认返回编辑框的文本,取消返回null;
open方法
window.open("url地址");
<html>
<head>
<meta charset="UTF-8">
<title>window</title>
</head>
<body>
</body>
<script>
// 使用时省略window.
/*var res = confirm("确认删除?");
alert(res);
var psd = prompt("输入密码:");
alert(psd);
alert(alert("xxx"));*/
open("./onload.html");
</script>
</html>
定时器
setTimeout(函数, 毫秒值);
clearTimeout(定时器名);
<html>
<head>
<meta charset="UTF-8">
<title>window定时器</title>
</head>
<body>
<input type="button" value="button" οnclick="closer()"/>
</body>
<script>
/*setTimeout(
function(){
alert("xxx");
},
3000
);*/
var timer;
var fn = function(){
alert("x");
timer = setTimeout(fn, 2000);
};
function closer(){
clearTimeout(timer);
};
fn();
</script>
</html>
setInterval(函数, 毫秒值);
clearInterval(定时器名);
<html>
<head>
<meta charset="UTF-8">
<title>window定时器</title>
</head>
<body>
<input value="button" type="button" οnclick="closer()"/>
</body>
<script>
var timer = setInterval(
function() {
alert("hello world!");
},
2000
);
var closer = function() {
clearInterval(timer);
};
</script>
</html>
5s倒计时跳转实例:
<html>
<head>
<meta charset="UTF-8">
<title>5s 跳转</title>
</head>
<body>
恭喜您注册成功,<span id="second" style="color:red">5</span>s后跳转到首页,如果不跳转请<a href="https://www.baidu.com">点击这里</a>
</body>
<script>
var t = 5;
var timer = setInterval(
function(){
var second = document.getElementById("second");
if (t >= 1){
second.innerHTML = t;
t--;
} else{
clearInterval(timer);
location.href = "https://www.baidu.com";
}
},
1000
);
</script>
</html>
2、location 用于跳转(不能省略location)
location.href="url地址";
3、history 历史对象(不能省略history)
back(); = go(-1)
forward(); = go(1)
go(int);
<html>
<head>
<meta charset="UTF-8">
<title>history</title>
</head>
<body>
<a href = "https://www.baidu.com">baidu</a>
<input type="button" value="上一页" οnclick="history.back()"/>
<input type="button" value="下一页" οnclick="history.forward()">
</body>
<script>
</script>
</html>
七、js的dom
1、理解一下文档对象模型
html文件加载到内存之后会形成一颗dom树,根据这些节点对象可以进行脚本代码的动态修改
在dom树当中 一切皆为节点对象
2、dom方法和属性
笔记见代码