二、JavaScript基础

2.1 基础

需要了解的HTML知识

标签 属性 意义
html 包含网页的HTML部分
head 包含页面的页头部分
script src 包含页面的脚本或对外部脚本文件的引用。其属性src 为外部脚本的位置
title 包含页面的标题
body 包含网页的内容
h1...h6 这些标签的内容作为标题信息
a href 连接到另一个网页, href 指定应该连接到的url

2.2 关于函数

函数(function)是一组执行某一任务的 JavaScript语句。每个函数必须有一个名称(除了一个非常少见的例外,这会在本书后面讨论),并可被脚本的其他部分调用。

2.3 使用外部js脚本

<script src="script02.js"></script> 

其中的js脚本内容

window.onload = writeMessage;
function writeMessage() {
 document.getElementById("helloMessage").innerHTML = "Hello, world!";
} 

解释:

  1. window.onload = writeMessage;
    这一行的第一部分 window.onload 是一个事件处理程序,等号后面是一个函数名 writeMessage。这一行的意思是“当窗口完成加载时,运行 writeMessage函数”。

注意:
其中的window.onload = writeMessage; 和window.onload = writeMessage() 区别:
带圆括号的函数名意味着正在调用这个函数;如果没有圆括号(就像这里的情况),就是将它赋值给事件处理程序,以便在此事件发生时运行它。

常用弹出框

警告: alert("xxxx");
确认框: confirm("xxxx");
提示框:prompt("xxxx");

2.4 用链接对对象进行重定向

这个 HTML 页面基于链接对用户进行重定向

<!DOCTYPE html>
<html>
<head>
 <title>Welcome to our site</title>
 <script src="script07.js"></script>
</head>
<body>
 <h2 class="centered">
 <a href="script04.html" id="redirect"> Welcome to our site... c'mon in!</a>
 </h2>
</body>
</html>

通过将重定向功能嵌入在代码中,用户甚至不知道你的脚本干预了链接的行为

window.onload = initAll;

function initAll() {
 document.getElementById("redirect").onclick = initRedirect;
}
function initRedirect() {
 window.location = "jswelcome.html";
 return false;
} 

这是启用了 JavaScript 功能的用户将看到的 HTML 页面

<!DOCTYPE html>
<html>
<head>
 <title>Our site</title>
</head>
<body>
 <h1>Welcome to our web site, which features lots of cutting-edge JavaScript</h1>
</body>
</html> 

解释:

  1. <a href="script04.html" id="redirect"> Welcome to our site... c'mon in!</a>
    其中如是用户没有启用js功能则会跳转到script04.html页面,但是 启用了js功能则会跳转到js脚本中的页面
  2. return false表示停止对用户单击的处理,这样就不会加载 href 指向的页面。防止跳转到script04.html页面

2.5 错误处理

使用 JavaScript 的try/throw/catch命令产生友好、有用的错误消息。
如下例:

window.onload = initAll;

function initAll(){
    var ans = prompt("Enter a number", "");
    try{
        if(!ans || isNaN(ans) || ans< 0) {
            throw new Error("Not a valid numer");
        }
        alert("the square root of" ans + is + Math.sqrt(ans));
    }catch(errMsg){
        alert(errMsg.message);
    }
}
posted @ 2017-10-13 13:43  hptjzzj  阅读(122)  评论(0编辑  收藏  举报