JavaScript学习笔记1

警告框、确认用户的选择、提示用户、重新定向。

html文档

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!DOCTYPE html>
<html>
<head>
<title>

</title>
<script>
window.onload = function(){
document.getElementById("myMessage").innerHTML = "Hello,nihao";
}
</script>
<script src="Day1.js"></script>
</head>
<body>
<h1 id="myMessage">

</h1>
</body>
</html>

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
//警告框
//confirm() 方法有一个参数 (向用户询问的问题) , 并根据用户的响应返回 true 或 false 。

if(confirm("Are you sure you want to do that?")){
alert("you said yes")
}else{
alert("you said no ")
}

/*传递给 prompt() 方法的是由逗号分隔的两段信息(正式的术语是参数) :向用户询问的问题和默
认回答。这个方法返回用户的响应或 null。*/

/*如果变量是在一个函数中创建的,那么它是这
个函数的局部(local)变量,其他函数不能访问它。如果它是在任何函数之外创建的,
它就是全局的(global) ,脚本中的所有代码都可以访问它。在这个脚本中,我们创建
了ans全局变量。 */


//提示用户
var ans = prompt("Are you sure want to do that?","");
if(ans){
alert("you said"+ans)
}else{
alert("you refused to answer")
}

/*
用链接对用户进行重定向
当完成页面加载时,它会触发 initAll() 函数。
这个函数告诉 id 为 change 的元素 (也就是步骤 1 中的链接) , 在它被单击时应该调用
Second函数。
*/
window.onload = intAll;
function intAll(){
document.getElementById("change").onclick = Second;

}
/*
如果调用这个函数, 它就将 window.location (即浏览器中显示的页面) 设置为一个新页面。 return
false 表示停止对用户单击的处理,这样就不会加载 href 指向的页面。
*/
function Second(){
window.location="index.html";
return false
}

this的用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
window.onload = initAll; 

function initAll() {
document.getElementById("redirect").onclick = initRedirect;
}
/*
JavaScript 关键字 this 使脚本能够根据使用这个关键字的上下文将值传递给函数。在这个示例
中, this 是在一个由标签的事件触发的函数中使用的,所以 this 是一个链接对象。只需将 this 看
做一个容器.
*/
function initRedirect() {
alert("We are not responsible for the content of pages outside our site");
window.location = this;
return false;
}

多级条件switch /case语句

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
window.onload = intAll;
//当加载页面时,调用 initAll() 函数

function intAll(){
document.getElementById("frist").onclick=Second;
document.getElementById("second").onclick=Second;
document.getElementById("third").onclick=Second;

/*在这个函数中,我们为页面上的每个按钮设置了 onclick 处理程序。因为在 HTML 中设置了 id
属性和 value 属性,所以可以使用 getElementById() 设置事件处理程序。如果有 value 属性,就可以使用 getElementByValue() 调用,那么就不必设置 id 属性。 */
}

function Second(){
//this 对象的 id 用作 switch() 的参数。这个值将决定执行以下 case 语句中的哪一个
switch(this.id){
case"frist":
alert("you clicked frist")
break;
case"second":
alert("you clicked second")
break;
case"third":
alert("you clicked third")
break;
}
}

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!