函数
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>MyGod</title> <script> function disp() //函数,一般写在head中 { alert("Hello World!"); //消息提示 } </script> </head> <body> <script type="text/javascript"> document.write("<h1> Hello World!</h1>"); //在页面上输出内容 </script> <input type="button" value="OK" onclick="disp()"> //点击按钮 </body> </html>
变量定义
//JavaScript变量是弱类型,对大小写敏感
//可用数据类型有: 整型、浮点型、布尔型、转义字符、字符串、空值(null)等
var x=5;
var flag=true;
var carname="Benz"
函数示例1
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>MyGod</title> <script> function show() { alert(document.getElementById("username").value); //得到id对应的对象,输出其值 } </script> </head> <body> <form> <input type="text" id="username"> <input type="button" onclick="show()" value="提交"> </form> </body> </html>
函数示例2
<html> <head> <script> function add(a,b) //参数不指定类型 { return a+b; } //有返回值也不能指定类型 </script> </head> <body> 6+5=<script>document.write(add(6,5))</script> </body> </html>
confirm函数
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>MyGod</title> <script> function exit_confirm() { var r=confirm("确认退出?"); if(r==true) { window.close(); } else return; } </script> </head> <body> <input type="button" onclick="exit_confirm()" value="退出"> </body> </html>
onblur(失去焦点事件)
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>MyGod</title> <script> function upperCase() { var x=document.getElementById("username"); x.value=x.value.toUpperCase(); } </script> </head> <body> 用户名: <input type="text" id="username" onblur="upperCase()"> <br> 年龄: <input type="text" id="age" onblur="alert(this.value)"> </body> </html>
onchange(内容修改并失去焦点)
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>MyGod</title> <script> function upperCase() { var x=document.getElementById("username"); x.value=x.value.toUpperCase(); } </script> </head> <body> <form> <select name="here" onchange="window.location=this.options[this.selectedIndex].value"> <option value= ""> 请选择 </option> <option value= "http://www.163.com"> 网易 </option> <option value="http://www.baidu.com"> 百度 </option> <option value= "http://www.sina.com">新浪 </option> <option value= "http://www.sohu.com">搜狐 </option> </select> </form > </body> </html>
onmouseover(鼠标经过)和onmouseout(鼠标离开)
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>MyGod</title> </head> <body> <h1 align="center" onmouseover="this.style.color='red'" onmouseout="this.style.color='green'" onclick="this.style.color='blue'">字体变色</h1> </body> </html>
onfocus(获得焦点)
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>MyGod</title> <script type="text/javascript"> function setStyle(x) { x.style.background="yellow" ; x.value=""; } function clsStyle(x) { x.style.background="white" ; } </script> </head> <body> <input type="text" value="请输入用户名" onfocus="setStyle(this)" onblur="clsStyle(this)"> </body> </html>