- 如果一行只有一个语句,建议在末尾使用分号 ;
<script> ...</script>
告诉浏览器后面代码是javascript- 函数: function name () { …} 和bash shell的函数定义完全一样的.
- 使用外部脚本
<script src="xxx.js"></script>
window.onload = writeMessage
意思是将函数直接赋值给事件处理程序,以便在事件发生时运行它.- 脚本中添加注释是一个良好习惯.
单行注释 : //
function writeMessage() {
// Here's where the actual work gets done
document.getElementById("helloMessage").innerHTML = "Hello, world!";
}
多行注释 : /* …..*/
/*
This is an example of a long JavaScript comment. Note the characters at the beginning and ending of the comment.
This script adds the words "Hello, world!" into the body area of the HTML page.
*/
window.onload = writeMessage; // Do this when page finishes loading
function writeMessage() {
// Here's where the actual work gets done
document.getElementById("helloMessage").innerHTML = "Hello, world!";
}
- 发出警告 (” danger”)
- 指出页面需要javascript
<noscript>
<h2>This page requires JavaScript.</h2>
</noscript>
条件选择:
if (conditon)
{A}
esle
{B}
等同于:m=(conditon)?A:B;
- 提示用户 promt(para1,para2)
实例:
// yes/no 是默认参数
var ans=prompt("Are you sure you want to do that?","yes/no");
if (ans) {
alert("You said " + ans);
}
else {
alert("You refused to answer");
}
- 对用户重定向
window.onload = initAll; // 完成页面加载后执行initALL函数
function initAll() {
document.getElementById("redirect").onclick = initRedirect;
}
/*
window.location(将浏览器中显示的页面设置为一个新页面)
*/
function initRedirect() {
window.location = "jswelcome.html";
return false; // 停止对用户单击的处理,不会加载href指向的页面
}
- 改进链接
window.onload = initAll;
function initAll() {
document.getElementById("redirect").onclick = initRedirect;
}
/* 脚本中的this可根据使用这个关键字的上下文将值传递给函数
比如:这里这个this 代表id=redirect 元素的内容*/
function initRedirect() {
alert("We are not responsible for the content of pages outside our site");
window.location = this;
return false;
}