转载请标明出处:http://blog.csdn.net/zhaoyanjun6/article/details/126501656
本文出自【赵彦军的博客】
函数定义
函数用 function
关键字声明,用 <script>
包裹起来
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>测试</title>
<script>
//无参数
function wri() {
document.write("hello")
}
//有参数
function wri2(num) {
document.write("hello " + num)
}
</script>
</head>
<body>
<button onclick="wri(3)">我是按钮</button>
<button onclick="wri2(3)">我是按钮</button>
</body>
</html>
效果如下:
函数调用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>测试</title>
<script>
//无参数
function wri() {
document.write("hello")
}
//有参数
function wri2(num) {
//函数调用
wri()
document.write("hello " + num)
}
</script>
</head>
<body>
<button onclick="wri2(3)">我是按钮</button>
</body>
</html>
效果:
打印日志
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>测试</title>
<script>
//有参数
function wri2(num) {
//信息
console.info("hello " + num)
//警告
console.warn("hello " + num)
//error
console.error("hello " + num)
}
</script>
</head>
<body>
<button onclick="wri2(3)">我是按钮</button>
</body>
</html>
打开调试模式:
效果:
函数返回值
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>测试</title>
<script>
//有返回值函数
function myFunction(a, b) {
return a + b;
}
c = myFunction(12,4)
console.log(c)
</script>
</head>
<body>
</body>
</html>