Javascript基础

推荐在线学习网站:

第一个JavaScript(JS)程序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<!DOCTYPE html>
<!--DOCTYPE不是HTML标签,它指定了HTML版本,此处说明版本HTML5-->
<html>
<head>
<!--<meta> 标签提供了HTML文档的元数据,这里指定页面编码字符集为UTF-8-->
<meta charset="UTF-8">
<title>我的第一个 JavaScript 程序</title>
<script>
// 在demo段落展示日期
function displayDate(){
/*
document 对象使我们可以从脚本中对 HTML 页面中的所有元素进行访问。
getElementById 返回对拥有指定 id 的第一个对象的引用。
*/
document.getElementById("demo").innerHTML=Date();
// 在浏览器调试控制台打印日志
console.log("控制台输出");
}
</script>
</head>
<body>

<h1>我的第一个 JavaScript 程序</h1>
<p id="demo">这是一个段落</p>

<button type="button" onclick="displayDate()">显示日期</button>

</body>
</html>

HTML引入JavaScript

script标签

JavaScript脚本必须位于 标签之间。

JavaScript代码可以直接嵌在网页的任何地方,但通常放置在HTML顶部或底部,不会干扰页面的内容。

  • head部分JavaScript脚本
  • body部分JavaScript脚本

引入外部JavaScript

HTML文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
<html>
<head>
<title>JavaScript练习</title>
<script src="/js/myScript.js"></script>
</head>
<body>

<h1>我的第一个 JavaScript 程序</h1>
<p id="demo">这是一个段落</p>

<button type="button" onclick="displayDate()">显示日期</button>
</body>
</html>

JS文件 myScript.js:

1
2
3
4
5
6
7
8
// 在demo段落展示日期
function displayDate(){
/*
document 对象使我们可以从脚本中对 HTML 页面中的所有元素进行访问。
getElementById返回对拥有指定 id 的第一个对象的引用。
*/
document.getElementById("demo").innerHTML=Date();
}

JS变量与函数

JavaScript的语法和Java语言类似,每个语句以;结束,但并非强制要求,语句块用{}

变量声明

变量名区分大小写,允许包含字母、数字、美元符号($)和下划线,但第一个字符不允许是数字,不用使用脚本语言中保留的关键字及保留符号作为变量名。

1
2
3
4
5
6
// 变量声明,只声明未赋值的变量值为undefined
var a;
// 变量声明并赋值
var a = 1;
// 隐式声明全局变量并赋值
a = 1;

函数声明与调用

1
2
3
4
5
6
7
8
// 函数定义
function add(op1, op2)
{
// 这里是要执行的代码
return op1 + op2;
}
// 执行函数
console.log(add(1, 2));

全局变量 vs 局部变量

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// 在函数块外定义的变量都是全局的
var a = 1;

function setValue()
{
// 在函数内部定义全局变量,不加var
b = 2;
// 定义局部变量用var
var c = 3;
// 函数内可访问全局变量
a = 11;
if (true){
var i = 3;
}
// 与Java不同,在函数内部的代码块{}定义的局部变量,在代码块外(函数内部)也能访问
console.log(i);
}

function log(){
console.log(a);
console.log(b);
console.log(c);
}

setValue();
log();

特殊情况:当局部变量与全局变量重名,局部变量会覆盖掉全局变量。建议命名不要重复。

1
2
3
4
5
6
7
8
9
10
11
12
13
var a = 1;

function testSameVarName()
{
/*
Javascript在执行前会对整个脚本文件的声明部分做完整分析(包括局部变量),从而确定实变量的作用域。
这里输出undefined,因为局部变量a覆盖了全局变量a,并且在此处还没有被赋值。
*/
console.log(a); // undefined
var a = 3;
console.log(a); // 3
}
testSameVarName();

JavaScript 数据类型

JavaScript 数据类型包括:字符串、数字、布尔、数组、对象、Null、Undefined

Number对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
y = 5;
// 加减乘除
x=y+2;
x=y-2;
x=y*2;
x=y/2;
// 求余数
x=y%2;
// 累加、递减
x++;
x--;
// 赋值运算符
x=y;
x+=y; // 等价于 x = x + y; 以下类推
x-=y;
x*=y;
x/=y;
x%=y;

String对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// 字符串可用''或""定义
txt="Hello world!"
// 字符串长度
txt_length = txt.length;
console.log(txt_length);
// 拼接字符串
txt = txt + "!!!";
// 把其他对象转为字符串
str_1 = 1 + "";
// 或者
str_1 = String(1)
// indexOf() 方法可返回某个指定的字符串值在字符串中首次出现的位置。
console.log(txt.indexOf("world"));
// replace() 方法用于在字符串中用一些字符替换另一些字符。
console.log(txt.replace("Hello", "Hi,"));
// split() 方法用于把一个字符串分割成字符串数组。
console.log(txt.split(" "));
// substring() 方法用于提取字符串中介于两个指定下标之间的字符。
console.log(txt.substring(0, txt.indexOf(" ")));

// 插入特殊字符用反斜杠
txt="We are the so-called \"Vikings\" from the north."
// 换行符
txt="line one. \nnew line"
// ' 在""字符串中无需转义,同理,"在''字符串中无需转义
txt='We are the so-called "Vikings" from the north.'

Array对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// Array对象可以包含任意数据类型
var arr = [1, 2, 3.14, 'Hello', null, true];
// 数组长度
console.log(arr.length); // 6
// 访问元素
console.log(arr[3]);
// 对元素操作,赋值
arr[3] = "Hello world!";
console.log(arr.indexOf(3.14)); // 元素3.14的索引为2
// push()向Array的末尾添加若干元素,pop()则把Array的最后一个元素返回并删除
arr.push('a');
console.log(arr.pop());
/*
splice() 方法向/从数组中添加/删除项目,然后返回被删除的元素。
arrayObject.splice(index,howmany,item1,.....,itemX)
index, 必需。整数,规定添加/删除项目的位置,使用负数可从数组结尾处规定位置。
howmany, 必需。要删除的项目数量。如果设置为 0,则不会删除项目。
item1, ..., itemX, 可选。向数组添加的新项目。
*/
// 从索引2开始删除3个元素,然后再添加两个元素:
arr.splice(2, 3, 'Google', 'Facebook');
// 只删除,不添加:
arr.splice(2, 2);

// 遍历数组的三种方法
for(var i=0; i < arr.length; i++){
console.log(arr[i]);
}
for (var i in arr){ // i是arr的索引,与上面的循环相同
console.log(i);
console.log(arr[i]);
}
arr.forEach(function(value, index, arr){
// 在forEach使用return会失效,break会报错
console.log(value); //当前值
console.log(index); //当前索引
console.log(arr); //原数组
});

对象

JavaScript 中的所有事物都是对象,提供多个内建对象,比如 String、Date、Array 等等。此外,JavaScript 允许自定义对象。对象只是带有属性方法的特殊数据类型。

JavaScript的对象是一种无序的集合数据类型,它由若干键值对组成。创建一个对象:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// 对象初始化器方式 
// 用一个`{ }`表示一个对象,键值对以`xxx: xxx`形式申明,用`,`隔开。
// 注意,最后一个键值对不需要在末尾加,,如果加了,有的浏览器(如低版本的IE)将报错。
var xiaohong = {
name: '小红',
id: 1,
// 如果属性名包含特殊字符,就必须用引号括起来
'middle-school': 'No.1 Middle School',
// 属性值可以是函数(方法)
sayHi: function(){
console.log('Hello world!');
}
};

// 构造函数方式
function Student(name, id, school){
this.name = name;
this.id = id;
this['middle-school'] = school;
this.sayHi = function(){
console.log('Hello world!');
};
}
xiaohong = new Student("小红", 1, 'No.1 Middle School');

访问对象的属性:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
var xiaohong = {
name: '小红',
id: 1,
'middle-school': 'No.1 Middle School',
sayHi: function(){
console.log('Hello world!');
}
};
// 用.访问对象的属性
console.log(xiaohong.name);
// 用引号定义的属性名,必须用obj['propertyName']的形式访问
console.log(xiaohong['middle-school']);
// 也可用此法访问一般的属性
console.log(xiaohong['id']);
// 运行对象的方法
xiaohong.sayHi();
// 访问不存在的属性返回undefined
console.log(xiaohong.age); // undefined
// 新增属性
xiaohong.age = 21;
// 删除属性
delete xiaohong.name; // 删除name属性
console.log(xiaohong.name); // undefined
// 判断属性是否存在
console.log('id' in xiaohong);

// 遍历对象的属性
for (var key in xiaohong){
console.log("key: "+key+", value: "+xiaohong[key]);
}

动态类型

JavaScript 拥有动态类型。相同的变量可用作不同的类型:

1
2
3
var x                // x 为 undefined
x = 6; // x 为数字
x = "Bill"; // x 为字符串

控制语句

比较运算符

1
2
3
4
5
6
7
8
9
10
11
12
x = 2;
// 抽象相等比较 ==,执行前执行类型转换
console.log(x == 2); // true
console.log(x == 1); // false
console.log(x == '2'); // true
// 严格相等比较 ===,值和类型都必须相等
console.log(x === '2'); // false
console.log(x != '2'); // false
console.log(x > '2'); // false
console.log(x >= '2'); // true
console.log(x < '2'); // false
console.log(x <= '2'); // true

逻辑运算符

1
2
3
4
5
x = 2;
console.log(x >= 0 && x <= 8); // true
console.log(x >= 3 || x <= 8); // true
console.log(! x >= 3); // false
console.log(! (x >= 3)); // true

if语句

1
2
3
4
5
6
7
8
time = 12;
if (time < 10){
console.log("Good morning");
}else if (time<20){
console.log("Good day");
}else{
console.log("Good evening");
}

switch语句

1
2
3
4
5
6
7
8
9
10
11
switch (day) {
case 0:
x = "Today it's Sunday";
break;
case 1:
x = "Today it's Monday";
break;
case 2:
x = "Today it's Tuesday";
break;
}

for循环

1
2
3
4
for (var i=0; i<5; i++)  {
x=x + "The number is " + i + "<br>";
}
// 其他例子参考Array对象、对象遍历部分

while循环

1
2
3
4
5
6
7
8
9
10
while (i<5) {
x=x + "The number is " + i + "<br>";
i++;
}

// do/while循环至少会执行一次
do {
x=x + "The number is " + i + "<br>";
i++;
} while (i<5);

jQuery

jQuery 是一个 JavaScript 库,极大简化了 JavaScript 编程。

jQuery是一个快速,小巧,功能丰富的JavaScript库,使得HTML 文档遍历和操作,事件处理,动画和Ajax 更加简单。

改写第一个JS程序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<html>
<head>
<title>用jQuery改写第一个JS程序</title>
</head>
<body>

<h1>我的第一个 JavaScript 程序</h1>
<p id="demo">这是一个段落</p>

<button type="button">显示日期</button>

<!--引用jQuery库-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
// $("button") 选择所有的button元素
$("button").on("click", function () {
// #id 选择器
$("#demo").html(Date());
});
</script>
</body>
</html>

选择器

参考RUNOOB.COM jQuery 选择器教程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>jQuery选择器示例</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>

<body>
<!--ID的命名规范:含字母、数字、连字符-、下划线_、冒号:、点号.,必须字母开头,大小写敏感。
建议只用字母数字命名id,避免jQuery转义-->
<p id="p1"> 第1段 </p>
<!--class 的命名规范,可参考 How to name css classes: http://bdavidxyz.com/blog/how-to-name-css-classes/-->
<p class="p-red"> 第2段 </p>
<p class="p-red p-gold"> 第3段 </p>
<p hidden="hidden"> 第4段 </p>
<p title="No.5"> 第5段 </p>
<hr />

用户名: &nbsp;<input type="text" name="username"><br>
密码: &nbsp;&nbsp;&nbsp;&nbsp;<input type="password" name="password" autocomplete="new-password"><br>
<hr />

<input type="checkbox" id="ckb_1" />
<input type="checkbox" id="ckb_2" disabled="disabled" />
<input type="checkbox" id="ckb_3" />
<input type="checkbox" id="ckb_4" />
<input type="button" id="btn" value="点击">
<hr />

<ul class="test">
<li>列表项</li>
<li>列表项
<ul>
<li>内嵌列表项</li>
</ul>
</li>
<li>列表项</li>
</ul>
<hr />

<p>这是ul元素后第1个p元素</p>
<div>
<p>这个p元素在div内</p>
</div>
<p>这是ul元素后第2个p元素</p>
<hr />

<ul>
ul
<li>
ul->li
<span id="embed_span">ul->li->span</span>
</li>
</ul>

<script type="text/javascript">
// * 选择器选取文档中的每个单独的元素,包括 html、head 和 body
$("*").css('color', '');
// # ID选择器选取带有唯一的指定 id 的元素。选择id=p1的元素
$("#p1").css('color','Violet');
// . 类选择器选取带有指定class的元素
$(".p-red").css('color','red');
// 标签选择器选取带有指定标签名的元素
$("p").css('color','Purple');

// 属性选择器
// 选择每个带有指定属性的元素
$("[hidden]").show();
// 选取每个带有指定属性和值的元素
$("[title='No.5']").css('color', 'Green');
// 选取每个不带有指定属性及值的元素
$("[class!='p-red']").css('color', 'yellow');
// 选取每个带有指定属性且以指定字符串结尾的元素
$("[class$='p-gold']").css('color', 'gold');

// :选择器
// 选择input元素
$(":input").css("background-color", "orange");
// 选择带有 type="text" 的 input 元素
$(":text").css("color", "orange");
// 选择带有 type="password" 的 input 元素
$(":password").css("background-color", "orange");

// 复合选择器,两个选择器相连
// 把类型为checkbox,同时"可用"的元素设置成"已选择"
// :checkbox选择带有 type="checkbox" 的 input 元素
$(':checkbox[disabled!="disabled"]').attr("checked",true);
$('input:checkbox[disabled!="disabled"]').attr("checked",true);

// ("parent descendant")选择器选取指定元素的后代的所有元素
$("ul.test li").css("color", "DarkBlue");
// ("parent > child") 选择器选取指定元素的直接子元素的所有元素。
$("ul.test > li").css("color", "DarkRed");
// ("element ~ siblings") 选择器选取指定元素 "element" 同级的所有元素。
$("ul.test ~ p").css("color","SkyBlue");
// ("element + next") 选择器选取指定元素"element" “紧邻”的同级元素"next"。
$("ul.test + p").css("color","yellow");

// :first 选择器选取第一个元素
$("ul.test ~ p:first").css('color', 'red');
// :last 选择器选取第一个元素
$("ul.test ~ p:last").css('color', 'red');
// :eq() 选择器选取带有指定 index 值的元素
$("ul.test ~ p:eq(1)").css('color', 'blue');

// parent() 方法返回被选元素的直接父元素
$("#embed_span").parent().css('color', 'blue');
// parents() 方法返回被选元素的所有祖先元素,它一路向上直到文档的根元素 (<html>)
$("#embed_span").parents().css('color', 'red');
// 可以使用可选参数来过滤对祖先元素的搜索
$("#embed_span").parents("ul").css('color', 'blue');
</script>
</body>
</html>

选择器-更复杂的例子

(改编自jQuery选择器-综合案例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>jQuery标签切换效果</title>
<script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script>
</head>

<body>
<!--代码部分begin-->
<div id="menu">
<!--tag标题-->
<div id="menu_female">
<h3>女装</h3>
<div class="tag" style="display: block;">
<dl>
<dd>
<p>第一类</p>
<a>1.衬衫</a>
<a>2.T恤</a>
<a>3.雪纺衫</a>
<a>4.针织衫</a>
<a>5.短外套</a>
<a>6.卫衣</a>
<a>7.小西裤</a>
<a>8.风衣</a>
<a>9.吊带背心</a>
<a>10.连衣裙</a>
<a name="setColor">11.蕾丝连衣裙</a>
<a>12.复古连衣裙</a>
<a>13.印花连衣裙</a>
<a>14.真丝连衣裙</a>
<a>更多</a>
</dd>
</dl>
</div>
<div class="tag_More" style="display:block">
<dl>
<dd>
<p>第二类</p>
<a>1.背带裤</a>
<a>2.哈伦裤</a>
<a>3.牛仔裤</a>
<a>4.休闲裤</a>
<a>5.小脚裤</a>
<a>6.西装裤</a>
<a>7.打底裤</a>
<a>8.阔脚裤</a>
<a>9.短裤</a>
<a>10.马甲/背心</a>
<a>11.羽绒服</a>
<a>12.棉服</a>
<a>13.夹克</a>
<a>14.POLO衫</a>
<a>更多</a>
</dd>
</dl>
</div>>
</div>
<div id="menu_male">
<h3>男装</h3>
<div class="tag" style="display:block">
<dl>
<dd>
<p>第一类</p>
<a>1.衬衫</a>
<a>2.T恤</a>
<a>3.牛仔裤</a>
<a>4.休闲裤</a>
<a>5.短裤</a>
<a>6.针织衫</a>
<a>7.西服</a>
<a>8.西裤</a>
<a>9.嘻哈裤</a>
<a>10.西服套装</a>
<a>11.马甲/背心</a>
<a name="setColor">12.羽绒服</a>
<a>13.棉服</a>
<a>14.夹克</a>
<p>更多</p>
</dd>
</dl>
</div>
<div class="tag_More" style="display:block">
<dl>
<dd>
<p>第二类</p>
<a>1.衬衫</a>
<a>2.T恤</a>
<a>3.牛仔裤</a>
<a name='setColor'>4.休闲裤</a>
<a>5.短裤</a>
<a>6.针织衫</a>
<a>7.西服</a>
<a>8.西裤</a>
<a>9.嘻哈裤</a>
<a>10.西服套装</a>
<a>11.马甲/背心</a>
<a>12.羽绒服</a>
<a>13.棉服</a>
<a>14.夹克</a>
<p>更多</p>
</dd>
</dl>
</div>
</div>
</div>

<script type="text/javascript">
// 找到男装下第一类衣服中的第一个p元素,并改变颜色
// :first-child 选择器选取属于其父元素的第一个子元素
$("#menu_male div.tag p:first-child").css('color','#9932CC');
</script>

<script type="text/javascript">
//找到男装下第一类衣服把a元素从顺序1-4加上颜色
//可以通过基本筛选器lt,选择匹配集合中所有索引值小于给定index参数的元素
$("#menu_male > div:first a:lt(4)").css('color','red');
</script>

<script type="text/javascript">
//找到男装所有a元素中属性名name="setColor"的元素,并设置颜色
//这里用的属性选择器[attribute='value']选择指定属性是给定值的元素
$("#menu_male a[name='setColor']").css('color','blue');
</script>

<script type="text/javascript">
//不分男女,选中第一类衣服中第9个a元素,并改变颜色
//:nth-child(n) 选择器选取属于其父元素的不限类型的第 n 个子元素的所有元素
$("#menu div.tag dd a:nth-child(10)").css('color','#66CD00');
</script>

<script type="text/javascript">
//找到女装下第一类衣服,把a元素中包含文字"更多"的节点,改变颜色
$(".tag:first a:contains('更多')").css('color','#C71585');
</script>
</body>
</html>

jQuery 元素绑定事件

一个限制输入框输入正整数的例子

1
2
3
4
5
6
7
8
9
10
11
12
请输入一个正整数:<input type="text" name="positive_num_inpt">

<script type="text/javascript">
// 限制输入框输入正整数
// on() 方法在被选元素及子元素上添加一个或多个事件处理程序
// 这里响应keyup事件。当键盘键被松开时发生 keyup 事件
$("[name='positive_num_inpt']").on("keyup", function(){
var tmptxt = $(this).val();
// /\D|^0/g 是一个正则表达式,匹配非数字与开头的0
$(this).val(tmptxt.replace(/\D|^0/g, ''));
});
</script>

jQuery Ajax

ajax() 方法通过 HTTP 请求加载远程数据。

ajax cnodejs.org论坛主题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$.ajax({
url: "https://cnodejs.org/api/v1/topics", // ajax请求地址,如果是跨域请求,需要服务器支持
type: "GET", // 请求方式 "POST" 或 "GET", 默认为 "GET"
dataType: "json", //根据返回数据类型可以有这些类型可选:xml html script json jsonp text,ajax会将数据解析成js对象
data: {limit: 3}, // 发送到服务器的数据。类型可以为:PlainObject、String、Array。GET 请求中将附加在 URL 后面
async: true, // 布尔值,默认是 true。表示请求是否异步处理。
success: function(data, status){
// 请求成功后执行此函数
console.log(data);
},
error: function(jqXHR, status, error){
// 请求失败要运行的函数
// 参数分别为:XMLHttpRequest对象,错误信息,捕获的错误对象(可选)
}
});

点击按钮生成下拉选择框:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<button type="button">显示部门下拉选择框</button>
<select id="departmentSelector" hidden="hidden"></select>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
// $("button") 选择所有的button元素
$("button").on("click", function () {
$.ajax({
url: "/helloworld/department/list",
dataType: 'json',
success: function (data) {
$("#departmentSelector").html("");
for(var i in data){
$("#departmentSelector").append(
'<option value ="' + data[i].departmentId + '">' + data[i].departmentName +
'</option>'
);
}
$("#departmentSelector").show();
}
});
});

常用函数

1
2
3
4
i = Number("30");
console.log(typeof i);
i = parseInt("30");
i = parseFloat("30");