案例1
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
alert('hello JavaScript')
</script>
<STYLE>
div{
width:100px;
height:100px;
background:blue;
}
</STYLE>
<script type="text/javascript" src="js/hello.js"></script>
</head>
<body>
第一个JavaScript程序
<hr>
<input type="button" value="点我" οnclick=alert("我被点了")>
<!--<a href="" οnclick="alert('超链接被触发了')">超链接</a>-->
<a href="javascript:alert('超链接被触发了')">超链接</a>
<div οnmοuseοver="alert('走开')">把鼠标移上来</div>
</body>
</html>
案例2
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
//变量
var name;
name ="tom";
// alert(name);
var age=18;//定义age,并且赋值18 age为整型变量
alert(age);
sex ="male";
alert(sex); //不建议使用
{
var x=8;
// alert(x);
let y=7;
alert(y);
}
// alert(x);
// alert(y);
姓名 ="tom";
alert(姓名);
</script>
</head>
<body>
</body>
</html>
案例3
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
// 输出
// alert("heihei")
// console.log("hhaha")
// document.write("xixi")
// 输入
// var name=prompt("请输入你的姓名")
// console.log(name);
// var age=prompt("请输入你的年龄:");
// console.log(age,age+2,typeof age);
// age = Number(age);
// console.log(age,typeof age);
// console.log(age+2);
console.log("he\'llo\n world");
</script>
</head>
<body>
</body>
</html>
案例4
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
<!--数据类型-->
//
// var name = 'tom';
// var age = 18;
// var height = 180.5;
// var flag = true;
//
// var hobby = null;
//
// var date = new Date();
//
// var arr = new Array();
//
// var sex;
// console.log(typeof name);
// console.log(typeof age);
// console.log(typeof height);
// console.log('hello'-5);
// console.log(typeof flag);
// console.log(typeof hobby);
// console.log(typeof date);
// console.log(typeof arr);
// console.log(typeof sex);
// 类型转换
// 转换为number
// var a = '12';
// console.log(a,typeof a);
// 使用number
// a = Number(a);
// console.log(a,typeof a);
// a = Number('12.5');
// a = number('12abc');
// a = Number('abc12');
///2.
// a = parseInt('12');
// a = parseInt('12.5'); // 转换时会去掉小数部分
// a = parseInt('12abc');//按照字符的顺序依次解析 abc12不可以转换
//3。
// a = parseFloat('12');
// a = parseFloat('12.5');
// a = parseFloat('12abc');
// a = parseFloat('abc12');
// var a = 12;
// console.log(a,typeof a);
// a = a + '';//后接一个空字符串
// console.log(a,typeof a);
// 布尔转换为数字
// var a;
// a = Number(false);
//转换为布尔
// var a = Boolean(0);
// var a = Boolean('');
// var a = Boolean(null);
// var a = Boolean(undefined);
// var a = Boolean(NaN);
// var a = Boolean(4);
// var a =Boolean('tom');
var name;
name = 'tom';
if(name){
console.log(name);
}
// console.log(a,typeof a);
</script>
</head>
<body>
</body>
</html>
案例5
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
//算术运算符
// var a =5;
// var b =3;
// var c ='0';
// var d =true;
// console.log(a+b);
// console.log(a-b);
// console.log(a*b);
// console.log(a/b);
// console.log(a%b);
// console.log(a**b);
// console.log(a-c);//数字字符可以转换为数值
// console.log(a+d);
// var a = 1;
// var b = 2;
// console.log(a++ + b++);//先使用a 的值再自加 输出a原本的值
// console.log(a,b);
// console.log(a);
// console.log(++a);//先自加减,再返回值 输出变化后a 的值
// console.log(a);
//比较运算
// var a = 5;
// var b = 3;
// console.log(a>b);
// console.log(a<b);
// console.log(a<=b);
// console.log(a>=b);
//返回值为true flase;
// var a = 5;
// var b = '5';
// console.log(a==b);//a b的内容是否相等
// console.log(a===b);//全等于 既要判断内容,也要判断类型
// var a = 1;
// var b =true;
// console.log(a=b);
// console.log(a==b);//再js 中true可以表示为1 false表示为0
//赋值运算符
// var a =8;
// a +=2;//a=a+2
// a -=2;//a=a-2
// console.log(a);
//逻辑运算符
// var x = true;
// var y = false;
// console.log(x && y);//&&并且运算符 两边为真才为真 一边为假就是假
// console.log(x || y);// \\或运算符 一边为真就是真 两边为假才是假
//逻辑短路问题
var a = 0;
var b = 5;
console.log(a && b);//0--false
console.log(a || b);
//条件运算符
var a =0;
var b =5;
console.log(a>b?a+b:a-b);//条件为真返回表达式1 的值,条件为假返回表达式2 的值
</script>
</head>
<body>
</body>
</html>
案例6
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
//使用math对象进行数学运算 Math.方法名(参数)
//绝对值
console.log(Math.abs(-5));
//幂运算
console.log(Math.pow(2,4));
//四舍五入
console.log(Math.round(123.456));//js不可以指定四舍五入到第几位
//向上取整,向下取整
console.log(Math.ceil(3.5));//取大于等于3.5的最小整数
console.log(Math.floor(3.5));//取小于等于3.5的最大整数
//生成随机数
console.log(Math.random());//产生0到1之间的随机数,以当前系统时间为随机数种子
//最大值,最小值
console.log(Math.max(23,4,12,3));
console.log(Math.min(23,322,42,5));
//圆周率的值
console.log(Math.PI);
</script>
</head>
<body>
</body>
</html>
案例7
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
var age = 25;
if(age>=60)
{
console.log('老年')
}
else if(age>=30)
{
console.log('中年');
}
else if(age>=16)
{
console.log('少年');
}
else
{
console.log('童年');
}
var day = '星期一';
switch (day) {
case '星期一': {
console.log('吃包子');
break;
}
case '星期二': {
console.log('吃包子');
break;
}
case '星期三': {
console.log('吃包子');
break;
}
}
</script>
</head>
<body>
</body>
</html>
案例8
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
var i = 1;
var sum = 0;
while(i<100)
{
sum+=i;
i++;
}
console.log(sum);
//do...while
var i =1;
var sum = 0;
do
{
sum+=i;
i++;
}while (i<101);
console.log(sum);
//for
var sum = 0;
for(var i = 1;i<-100;i++)
if(i%7!=0);
sum+=i;
console.log(sum);
//for...in对集合进行遍历
var str ='welcome';//将字符串看作是由多个字符组成的集合
for(var index in str)
{
// console.log(c);//输出了str索引
console.log(str[index]);
}
// s ='abc';
// document.write(s[0]);
// document.write(s[1]);
// document.write(s[2]);
//break continue
for(var i =1;i<=10;i++)
{
if(i%2==0)
break;
console.log(i);
}
</script>
</head>
<body>
</body>
</html>
案例9
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
// var arr = new Array();
// arr [0] =12;
// arr [1] =9;
// console.log(arr.length);
// console.log(arr[0]);
// console.log(arr[1]);
// var arr = new Array('tom','jack','alice');
// console.log(arr);
// console.log(arr[2])
// console.log(arr[arr.length-1]);
// var arr = ['tom','jack','alice','mack'];
// console.log(arr[arr.length-1]);
// console.log(arr[0]);
//1到100之间所有能被3整除的数字,放到数组nums中,输出这个数组,并统计个数
// var arr =[];
// for(var i=1;i<=100;i++)
// if(i % 3==0){
// arr[arr.length] = i;
// //每次向数组中添加元素时,length属性值都会改变
// }
// console.log(arr)
var arr = ['tom','jack','alice','make'];
// var arr = [21,3,34,2,45,643,453]
// console.log(arr);//未排序的结果
// arr.sort();
// console.log(arr);//排序后的结果
console.log(arr);
// arr.reverse();
// console.log(arr.join('-'));
console.log(arr.indexOf('jack'));
console.log(arr.lastIndexOf('jack'));
console.log(arr.slice(1,4));
console.log(arr.slice(1));
</script>
</head>
<body>
</body>
</html>
案例10
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
// var arr = new Array();
// arr[0] = new Array();
// arr[1] = new Array();
// arr[0][0]=12;
// arr[0][1]=9;
// arr[1][0];
//
var arr = [
[31,78,99,6],
[23,44,54,5],
[23,44,63,7]
]
// console.log(arr[0][1]);
// console.log(arr[2][1]);
for (var i = 0;i<arr.length;i++)
{
for(var j = 0;j<arr[i].length;j++)
document.write(arr[i][j]+' ');
document.write('<br>');
}
</script>
</head>
<body>
</body>
</html>
案例11
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
/*
自定义函数
*/
//1.定义函数
function show() {
console.log('heihei')
}
function calc(num1,num2,num3) {//形式参数
//console.log(num1,num2,num3);
var sum = num1+num2+num3;
// console.log(sum);
return sum;
}
//2.调用函数 有两个功能 返回值
//show()
var result = calc(12,6,3);//实际参数
//console.log(result);
//3.变量的作用域
// var a = 6;//在函数外定义的全局变量
// function fn()
// {
// var a=5;//在函数内部定义的局部变量
// console.log(a);
// console.log(c);
// }
// fn();
function fn()
{
if(true)
{
var a = 5;
//let a = 5;
console.log(a);
}
console.log(a);
}
fn();
// {
// var d =2;
// let x =4;
// console.log(x);
// }
// console.log(x);
//console.log(a);
//console.log(c);
</script>
</head>
<body>
</body>
</html>
案例12
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
function f1() {
console.log('111');
}
//fn();
//当单击窗口时执行fn函数
window.onclick = f1;
/*
函数本身也是一种数据类型
数据类型 string、number、boolem
*/
var a = f1;
// console.log(typeof a);
// a();
//将一个函数作为另外一个函数的参数
function f2(x,y) {
console.log(x);
//console.log(y);
y();//调用了f1函数
}
f2(5,f1);//当f1函数作为实际参数时,并没有执行,只是将函数体中的代码打印执行
/*
示例
*/
var arr = [12,4,23,6,26,85];
//定义比较器
//如果 第一个参数大于第二个参数,则返回正数
//如果第一个函数小于第二个参数,则返回负数 相等返回0
function comparFn(a,b) {
return b-a;
// if(a,b)
// return 1;
// else if(a>b);
// return -1;
// else if(a=b);
// return 0;
}
// console.log(arr);
// arr.sort();
// console.log(arr);
for(var index=0;index<arr.length;index++);
console.log(index,arr[index]);
function show(value,index) {
console.log(index,value);
//console.log(value);
}
arr.forEach(show);
</script>
</head>
<body>
</body>
</html>
案例13
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
//1.一般用于回调
// function show()
// {
// console.log('111');
// }
// window.οnclick=show;
window.onclick = function ()
{
console.log('1111');
};
function f1(){
console.log(222);
}
//var a = f1;//如果单纯要把f1赋值给
var a = function () {
console.log(222);
};
var arr = [12,24,236,2,86];
// function show(value,index) {
// console.log(index,value);
// }
// arr.forEach(show);
arr.forEach(function (value,index){
console.log(index,value);
});
// 2.自执行函数
// function fn() {
// console.log(333);
// }
// fn();
(function (){
console.log(333);
}) ();
</script>
</head>
<body>
</body>
</html>
案例14
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
//箭头函数的语法:
//参数 => 返回值
// var a = function (x) {
// return x*2
// }
// console.log(a(3));
var a = x => x*2; //优点:语法更加简洁
//console.log(a(3));
//示例2 如果箭头函数没有参数或有2个以上的参数,则必须使用小括号表示参数部分
var a = function () { //function ();
return 5;
}
var a = () => 5; //var a = ()=>5;
console.log(a());
//示例3
var a = function (x,y) {
var sum=x+y;
return sum;
// return x+y;
}
var a = (x,y) => {
var sum = x+y;
return sum;
};
// var a = function (x) {
// console.log(x);
// };
var a = x => console.log(x);
a(5);
//应用场景
var arr = [12,24,236,2,86];
arr.forEach((value,index)=>{
console.log(value,index)
});
</script>
</head>
<body>
</body>
</html>
案例15
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
var str = " Welcome to JS hello world ";
// console.log(str.charAt(0),str.charAt(3),str[0],str[str.length-1]);
// console.log(str.indexOf('o'));
// console.log(str.lastIndexOf('o'));
//
// console.log(str.toLocaleLowerCase());
// console.log(str.toLocaleUpperCase());
//
// console.log(str.substring(1,4));//左闭右开,不包含右边
// console.log(str.substring(1));//从1取到末尾
console.log(str);
console.log(str.length);
str = str.trim();
console.log(str.trim());
// str = str.replace('JS','JavaScript');//替换后将副本赋值给str
// console.log(str.replace('JS','JavaScript'));
// console.log(str.split(''));
// console.log(str.split('',3));
console.log(str.length);
// var str = new String('welcome to JS');
//console.log(str.length);
//console.log(typeof str);
</script>
</head>
<body>
</body>
</html>
案例16
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
var date = new Date();
//var date = new Date(2000,5,16,9,7,53);//月份的取值为0到11
// var date = nwe Date(123434253325);
//console.log(typeof date);
// console.log(date);
var year = date.getFullYear();
var month = date.getMonth()+1;
var d = date.getDate();
var hour = date.getHours();
var minute = date.getMinutes();
var second = date.getSeconds();
let millseconds = date.getMilliseconds();
let day = date.getDay();//返回一周中的第几天
let time = date.getTime();
console.log(time);//与1970年1月1日0时相差的毫秒数
console.log(day);
console.log(millseconds);
console.log(year,month,d,hour,minute,second,);
var weekday = ['星期日','星期一','星期二','星期三','星期四','星期五','星期六']
var currentime = checkdDate(year) +'年'+checkdDate(month) +'月'+checkdDate(d) +'日,'+ checkdDate(hour) +':'+ checkdDate(minute) +':'+ checkdDate(second) + ','+ weekday[day];
console.log(currentime);
function checkdDate(num) {
if(num<10)
return '0'+num;
else
return num;
}
</script>
</head>
<body>
</body>
</html>
案例17
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
//定义一个JSON对象
// var user = {
// "id":1001,
// "name":"tom",
// "age":20,
// "height":180.5,
// "address": {
// "province": "山西省",
// "city": "太原市",
// "district": "迎泽区"
// },
// "ismarried":true
// };
//访问方式:对象名
// console.log(user.name);
// console.log(user.height);
// console.log(user.address);
//JSON对象的集合
//var num = [12,3,23,5,23,64],
var users = [
{
"id":9527,
"name":"tom",
"password":"123",
"status":1
},
{
"id": 9528,
"name": "xx",
"password": "222",
"status": 0
},
{
"id":3333,
"name":"haha",
"password":"7777"
},
{
"id":4444,
"name":"alice",
"password":"8888"
},
]
for(var i = 0;i<users.length;i++)
{
var u = users[i];
console.log(u.id,u.name,u.password);
}
//JSON对象和字符串之间的转化
//1.将JSON对象转换成字符串
// console.log(typeof user);
// console.log(user);
// var str = JSON.stringify(user);
// console.log(typeof str);
// console.log(str);
//2.字符串转换为JOSN对象
// var str = "{'name':'tom','age':20,'sex':'男'}";
// var str = '{"name":"tom","age":20,"sex":"男"}';
//var obj = JSON.parse(str);
// console.log(typeof str);
// console.log(str);
// console.log(typeof obj);
// console.log(obj);
var users = '[{"id":1,"username":"tom"},{"id":"2","username":"jack"}]'
console.log(typeof users);
var objs = JSON.parse(users);
console.log(objs);
</script>
</head>
<body>
</body>
</html>
案例18
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
var stu = new Object();
//添加属性
stu.name = "tom";
stu.age = 20;
stu.height = 180.5;
//添加方法
stu.study = function() {
console.log('我叫'+ stu.name + '正在学习')
};
stu.run = function () {
console.log(stu.name+"正在参加马拉松...");
};
//调用属性
// console.log(stu.name,stu['age']);
// stu.study();
// stu.run();
//使用构造函数的方式
var date = new Date(2020,5,20);
console.log(date,typeof date);
function Student(name,age,sex) {
this.username = name;
this.age = age;
tuis.sex = sex;
this.show = function () {
console.log(this.username+'正在学习...');
}
}
//Student ('tom','20','male');
// var student = new Student('tom',20,'male');
// console.log(student.username,student.age,student.sex);
//使用JSON对象
var student ={
"name":"admin",
"age":18,
"sex":"male",
"study":function () {
console.log(student.name+'正在学习中');
}
};
console.log(student.name,student.age);
student.study();
</script>
</head>
<body>
</body>
</html>
案例19
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
// function query() {
// console.log(111);
// var objs = document.getElementsByName("hobby");
// console.log(typeof objs);
// console.log(objs);
// for (var i in objs);
// // console.log(objs[i]);
// var objs = document.getElementsByTagName("input");
// for (var i in objs);
// console.log(bojs[i]);
//4.根据CSS选择器来过去单个对象
// var obj = document.querySelector("#div2");
// var obj =document.querySelector("p.aaa");
// console.log(typeof obj);
// console.log(obj);
//5.根据CSS选择器来获取多个对象
var objs = document.querySelectorAll(".aaa");
console.log(objs.length);
console.log(objs);
//6.根据已有节点获取其他节点
// document.getElementById("second");
// console.log(obj);
// console.log(obj.parentNode);
// console.log(obj.previousSibling);
// console.log(obj.previousSibling.previousSibling);
console.log(obj.parentNode.firstChild);
console.log(obj.parentNode.lastChild);
}
</script>
</head>
<body>
<input type="button" value="获取页面中的元素" onclick="query()">
<div id="mydiv">hello</div>
<!--<div id="mydiv">world</div>-->
<div id="div2" class="aaa">world</div>
<p class="aaa">welcome</p>
爱好:<input type="checkbox" value="eat" name="hobby">吃饭
<input type="checkbox" value="sleep" name="hobby">睡觉
<input type="checkbox" value="doudou" name="hobby">打豆豆
<ul>
<li>tom</li>
<li id="second">jack</li>
<li>alice</li>
<li>mike</li>
</ul>
</body>
</html>
案例20
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.hello{
width: 500px;
height: 300px;
background: pink;
font-size: 50px;
}
</style>
<script>
function getProperty() {
// console.log(111);
// let obj = document.getElementById("baidu");
// console.log(typeof obj,obj);
// console.log(obj.href);
// console.log(obj.target);
// let obj = document.getElementById("male");
// console.log(obj.checked);
// var obj = document.getElementById("baidu");
// obj.href="http://www.sxgjpx.net";
// obj.target="_self";
var obj = document.getElementById("female");
obj.checked = true;
}
function getContent() {
var obj = document.getElementById("mydiv");
// console.log(obj.innerHTML);
// console.log(obj.innerText);
// obj.innerHTML = "<h2>你好世界<h2>";
// obj.innerText = "<h2>你好世界<h2>";
}
function getStyle() {
let obj = document.getElementById("mydiv");
console.log(obj.style);
// 设置CSS样式
// obj.style.width='300px';
// obj.style.height='400px';
// obj.style.background='pink';
// obj.style.fontSize='20px';
//一般设置类选择器来设置样式
obj.className='hello';
console.log(obj.className);
}
</script>
</head>
<body>
<input type="button" value="获取属性" onclick="getProperty()">
<input type="button" value="访问内容" onclick="getContent()">
<input type="button" value="访问CSS" onclick="getStyle()">
<hr>
<br>
<!--< a href=" " target="_blank" id="baidu">百度</ a>-->
<a href="https://www.baidu.com" target="_blank" id="baidu">点我</a><br>
用户名:<input type="text" name="username" id="username" value="">
姓名: <input type="radio" name="sex" value="male" id="male" >男
<input type="radio" name="sex" value="female" id="female" >女
<hr>
<div id="mydiv" class="hello">
<p>
啦啦啦
</p >
</div>
</body>
</html>
案例21
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#logo{
width:100px;
height:50px;
}
</style>
<script>
function change() {
if ($("baidu").checked){
$("logo").src="images/baidu.png";
$("tztSearch").name="wd";
$("frmSearch").action="https://www.baidu.com/s";
$("btnSearch").value="百度搜索";
}else if($("sogou").checked){
$('logo').src="images/sogou.png";
$("txtSearch").name="query";
$("frmSearch").action="https://www.sogou.com/web";
$("btnSearch").value="搜狗搜索";
}else{
$('logo').src="images/360.png";
$("txtSearch").name="q";
$("frmSearch").action="https://www.so.com/s";
$("btnSearch").value="360";
}
}
//用来简化元素的获取
function $(id){
return document.getElementById(id);
}
</script>
</head>
<body>
<input type="radio" name="search" id="baidu" checked onclick="change()"><label for="baidu">百度</label>
<input type="radio" name="search" id="sogou" onclick="change()"><label for="sogou">搜狗</label>
<input type="radio" name="search" id="360" onclick="change()"><label for="360">360</label>
<form action="https://www.baidu.com/s" id="frmSearch">
<img src="images/baidu.png" id="logo">
<input type="text" name="wd" id="txtSearch" placeholder="请输入关键字">
<input type="submit" id="btnSearch" value="百度搜索">
</form>
</body>
</html>
案例22
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
function doAdd() {
//创建一个li
//1.创建元素的节点
var li = document.createElement("li");
//2.设置文本内容
// var txt = document.createTextNode("alice");
// li.appendChild(txt);
li.innerText="alice";
// console.log(li);
//3.设置属性
// li.id="fourth";
li.setAttribute("id","fourth");
// console.log(li.getAttribute("id"));
console.log(li);
//4.将li添加到ul中,添加到节点中
//var ul =document.getElementById("myul");
// ul.appendChild(li);
//5.将li添加到jack的前面
//ul.insertBefore(li,document.getElementById("second"));
//6.替换节点 用ul中的alice替换jack
ul.replaceChild(li,document.getElementById("second"));
}
function doDelete() {
//删除当前节点
// document.getElementById("first").remove();
//var ul = document.getElementById("myul");
// ul.removeChild(document.getElementById("first"));
ul.removeChild(ul.lastChild);
}
</script>
</head>
<body>
<input type="button" value="添加" onclick="doAdd()">
<input type="button" value="删除" onclick="doDelete()">
<ul id="myul">
<li id="first">tom</li>
<li id="second">jack</li>
<li>mike</li>
</ul>
</body>
</html>
案例23
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
function f1() {
console.log(111);
}
window.onload = function () {
// var btn2 = document.getElementById("btn2");
// console.log(btn2);
// btn2.οnclick=function () {
// console.log(222);
// };
// document.getElementById("btn2").οnclick=function () {
// console.log(222);
// };
document.getElementsByName("btn2").onclick = f1;
document.getElementById("btn2").onclick = function () {
console.log(222);
console.log(event);
console.log(this);
console.log(event.srcElement);
};
var hobbies = document.getElementsByName("hobby");
console.log(hobbies);
for (var i = 0; i < hobbies.length; i++)
{
hobbies[i].onclick = function () {
//console.log(hobbies[i]);
console.log(this.value);
};
}
};
</script>
</head>
<body>
<!--1.方式1:静态绑定-->
<!--<input type="button" value="按钮1" onclick="alert('哈哈')">-->
<input type="button" value="按钮1" onclick="f1()">
<!--2.动态绑定-->
<input type="button" value="按钮2" id="btn2">
爱好:<input type="checkbox" name="hobby" value="eat">吃饭
<input type="checkbox" name="hobby" value="sleep">睡觉
<input type="checkbox" name="hobby" value="da">打豆豆
</body>
</html>
案例24
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#container{
text-align:center;
}
#mytable{
width:500px;
text-align:center;
border:1px solid #ccc;
margin:0 auto;
}
#mytable td,#mytable th{
border: 1px solid #ccc;
}
#mytable tfoot td{
text-align:right;
}
#myfrom tfoot td:first-child{
text-align: center;
}
</style>
<script>
window.onload=function () {
$("btnAdd").onclick=function () {
//添加功能 为添加按钮绑定事件
var tr= document.createElement("tr");
var tdName= document.createElement("td");
var tdAge= document.createElement("td");
var tdSex= document.createElement("td");
var tdPhone= document.createElement("td");
var tdDelete= document.createElement("td");
//将数据添加到td中
tdName.innerText=$("name").value;
tdAge.innerText=$("age").value;
tdSex.innerText=$("m").checked?$("m").value:$("f").value;
tdPhone.innerText=$("phone").value;
//创建inpuut
var btnDelete=document.createElement("input");
btnDelete.type="button";
btnDelete.value="删除";
btnDelete.onclick=function () {
this.parentElement.parentNode.remove()
};//添加的按钮可以删除行
tdDelete.appendChild(btnDelete);
//将td添加到tr
tr.appendChild(tdName);
tr.appendChild(tdAge);
tr.appendChild(tdSex);
tr.appendChild(tdPhone);
tr.appendChild(tdDelete);
//将tr添加到tbody
$("tb").appendChild(tr);
};
//每行的删除按钮绑定事件
var btnDeletes = document.querySelectorAll(".delete");
for(var i =0;i<btnDeletes.length;i++)
{
btnDeletes[i].onclick=function () {
this.parentNode.parentNode.remove();
};
}
//为首行
$("btnDeleteFirst").onclick=function () {
$("tb").getElementsByTagName("tr")[0].remove();
};
//为末行
$("btnDeleteLast").onclick=function () {
var trs = $("tb").getElementsByTagName("tr");
trs[trs.length-1].remove();
}
};
function $(id) {
return document.getElementById(id);
}
</script>
</head>
<body>
<div id="container">
<table id="mytable">
<thead>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>电话</th>
<th>操作</th>
</tr>
</thead>
<tbody id="tb">
<tr>
<td>tom</td>
<td>23</td>
<td>male</td>
<td>123</td>
<td><input type="button" value="删除" class="delete"></td>
</tr>
<tr>
<td>jack</td>
<td>19</td>
<td>male</td>
<td>246</td>
<td><input type="button" value="删除" class="delete"></td>
</tr>
<tr>
<td>alice</td>
<td>24</td>
<td>famale</td>
<td>754</td>
<td><input type="button" value="删除" class="delete"></td>
</tr>
</tbody>
<tfoot>
<td colspan="5">
<input type="button" value="从首行删除" id="btnDeleteFirst">
<input type="button" value="从末行删除" id="btnDeleteLast">
</td>
</tfoot>
</table>
<form action="" id="myfrom">
姓名:<input type="text" id="name">
<br>
年龄:<input type="text" id="age">
<br>
性别:
<input type="radio" name="sex" id="m" value="male">男
<input type="radio" name="sex" id="f" value="male">女
<br>
电话:<input type="text" id="phone">
<br>
<hr>
<input type="button" value="添 加" id="btnAdd">
<input type="button" value="删 除">
</form>
</div>
</body>
</html>
案例25
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#username{
outline: none;
}
.txtborder{
border:1px solid red;
}
#img{
width:160px;
height: 160px;
}
</style>
<script>
window.onload=function () {
//鼠标事件
// document.getElementById("btn").οnclick=function() {
// document.getElementById("btn").οndblclick=function () {
// document.getElementById("btn").οnmοuseοver=function () {
// document.getElementById("btn").οnmοusedοwn=function () {
// console.log(111);
// };
// document.getElementById("btn").οnmοuseοut=function () {
// document.getElementById("btn").οnmοuseup=function () {
// document.getElementById("btn").onmousemove = function () {
// console.log(222);
// };
//键盘事件
// document.getElementById("username").onkeydown = function () {
// console.log(111)
// };
// document.getElementById("username").onkeydown = function () {
document.getElementById("username").onkeyup = function (event) {
console.log(222);
};
//表单事件
// document.getElementById("username").οnfοcus=function (event) {
// console.log(111);
// this.className="txtborder";
// };
// document.getElementById("username").οnblur=function () {
// console.log(222);
// this.className="txtborder";
// };
document.getElementById("head").onchange=function () {
// console.log(111);
// console.log(this.files);
document.getElementById("img").src=window.URL.createObjectURL(this.files[0])
};
// document.getElementById("username").οnselect=function () {
// console.log(222);
// };
document.getElementById("frm").onsubmit = function () {
console.log(111);
// return true;//允许提交
return false;//禁止提交
};
};
</script>
</head>
<body>
<form action="" id="frm">
<input type="button" value="点我" id="btn">
用户名:<input type="text" id="username" name="username"><br>
<img src="" id="img"><br>
头像:<input type="file" id="head" multiple><br>
<input type="submit" value="提 交">
</form>
</body>
</html>
案例26
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
div{
width: 200px;
height: 200px;
background: pink;
}
p{
width: 100px;
height: 100px;
background: #CCC;
}
</style>
<script>
function f1(event) {
// console.log(event);
//event.stopPropagation();//阻止事件冒泡,w3c标准方式
event.cancelBubble=true;
alert(111);
}
window.onload=function () {
//绑定鼠标右键单击事件
document.getElementById("btn").oncontextmenu=function () {
event.preventDefault();//阻止事件的默认行为
this.style.color="red";
};
document.getElementById("mya").onclick=function () {
event.preventDefault();//阻止事件的默认行为
this.innerHTML="新浪";
};
};
</script>
</head>
<body>
<div onclick="alert(333)">
<p onclick="alert(222)">
<!--<input type="button" value="点我" οnclick="alert(111)">-->
<input type="button" value="点我" onclick="f1(event)" id="btn">
</p>
</div>
<a href="https://www.baidu.com" target="_blank" id="mya">百度</a>
</body>
</html>
案例27
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
function getDegree() {
var degree = document.getElementById("degree");
//console.log(degree.length);
//console.log(degree.selectedIndex);
//console.log(degree.value);
var opts = degree.options;
//console.log(opts);
//console.log(opts[degree.selectedIndex]);
// var opt = opts[degree.selectedIndex];
// console.log(opt,opt.value);
// opts[1].text="中专";
// opts[1].value="zhongzhuan";
//向下拉列表中追加一条信息
// console.log(opts[opts.length]);
// opts[opts.length].text="博士";
// opts[opts.length].value="boshi";
// var option = document.createElement("option");
// option.innerText="博士";
// option.value="boshi";
// degree.appendChild(option);
// opts[opts.length]=new Option("博士","boshi");
// var option = new Option("博士","boshi");
// degree.add(option);
//在高中前插入一个中专
var option = new Option("中专","zhongzhuan");
degree.add(option.document.getElementsByTagName("option")[1]);
}
window.onload=function () {
document.getElementById("degree").onchange=function () {
//console.log(111);
// console.log(this.options[this.selectedIndex].value);
console.log(this.value);
};
};
</script>
</head>
<body>
<input type="button" value="操作下拉列表" onclick="getDegree()">
<hr>-
学历:
<select name="" id="degree">
<option value="()">请选择学历</option>
<option value="gaozhong">高中</option>
<option value="dazhuan">大专</option>
<option value="benke">本科</option>
<option value="yanjiusheng">研究生</option>
</select>
</body>
</html>
案例28
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
var provinces = [
{
id:1001,
name:"哈哈哈",
cities:[...]
},
{
id:1002,
name:"啦啦省",
cities:[...]
},
{
id:1003,
name:"嘿嘿省",
cities:[...]
}
];
window.onload=function () {
//初始化省份
for(var i in provinces){
var p = provinces[i];
var option = new Option(p.name,p.id)
document.getElementById("province").add(option);
}
}
function change() {
//清空城市数据
document.getElementById("city").length=0;
//获取选择的省份
var pid = document.getElementById("province").value;
if(pid==0){
document.getElementById("city").add(new Option("--请选择城市--"));
return;
}
for(var i in provinces){
var p = provinces[i];
if(p.id==pid){
//添加城市
var cities = p.cities;
for(var j in cities){
var option = new Option(cities[j].name,cities[j].id);
document.getElementById("city").add(option);
}
return;
}
}
}
</script>
</head>
<body>
省份:
<select id="province" onchange="change()">
<option value="0">--请选择省份</option>
</select>
城市:
<select id="city">
<option value="0">--请选择城市--</option>
</select>
</body>
</html>
案例29
<<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
// document.getElementById()
// window.history
// window.location
//
// window常用方法
// 1.alert()
// window.alert(111);
// alert(111);
// 2.prompt();
// var name = window.prompt("请输入用户名","无名氏");
// console.log(name);
// 3.confirm
// var flg = confirm("确定要删除吗?")
// console.log(flg);
//
// 4.open()
// function f1() {
// open("test.28.html","test28","width=200px,height=200px,resizable=no");
// }
// 5.setTimeout
var timer_one;
function f2() {
timer_one = setTimeout(function () {
console.log(111);
},3000);//单位毫秒
}
// function show() {
// console.log(111);
// }
// setInterval()
var timer_zq;
function f3() {
timer_zq = setInterval(function () {
console.log("起床了!!!")
},1000);
};
// 周期性计时器使用一次性计时器能否实现
// function f2() {
// setTimeout(show,1000);//单位毫秒
// }
// function show() {
// console.log(111);
// setTimeout(show,1000);
// }
// 7.clearTimeout()
function f5() {
clearInterval(timer_zq);
}
// window的常用事件
// window.onload
window.onscroll=function () {
console.log(222);
}
window.onclick=function () {
console.log(333);
}
window.onload=function () {
console.log(444);
}
//一个对象可以绑定多个事件,但是一个hi见不能绑定多次
window.onload=function () {
console.log(555);
}
</script>
</head>
<body>
<input type="button" value="打开一个新窗口" onclick="f1()"> <br>
<input type="button" value="一次性计时器" onclick="f2()"> <br>
<input type="button" value="周期性计时器" onclick="f3()"> <br>
<input type="button" value="关闭一次性计时器" onclick="f4()"> <br>
<input type="button" value="关闭周期性计时器" onclick="f5()"> <br>
<hr>
<p style="background:pink;height:2000px">
hello world!
</p>
</body>
</html>
案例30
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
function f1() {
// console.log(location.href);//获取location的href属性
location.href="https://www.baidu.com";
// location.reload();
}
function f2() {
history.back();
}
function f3() {
history.forward();
}
</script>
</head>
<body>
<input type="button" value="操作location" onclick="f1()"> <br>
<input type="button" value="后退" onclick="f2()"> <br>
<input type="button" value="前进" onclick="f3()"> <br>
</body>
</html>
案例31
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
var timer;
var l=0,r=0;
function doStart() {
$("start").disabled=true;
$("stop").disabled=false;
timer =setInterval(function () {
r++;
if(r>9) {
r=0;
l++;
}
if (l>9) {
r=0;
l=0;
}
$("imgr").src="images/number/"+r+".bmp";
$("imgl").src="images/number/"+l+".bmp";
},100);
}
function doStop() {
$("stop").disabled=true;
$("start").disabled=false;
clearInterval(timer);
}
function $(id) {
return document.getElementById(id);
}
</script>
</head>
<body>
<table>
<tr>
<td><img src="images/number/0.bmp" id="imgl"></td>
<td><img src="images/number/0.bmp" id="imgr"></td>
</tr>
<tr>
<td><input type="button" value="开始" id="start" onclick="doStart()"></td>
<td><input type="button" value="停止" id="stop" onclick="doStop()" disabled></td>
</tr>
</table>
</body>
</html>
案例32
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
//定义正则表达式对象
// var reg = /a/;
// console.log(reg.test("heAllo"));
//方式2:定义正则表达式对象
// var reg = new RegExp('a','i');
// console.log(reg.test('hellowaA'))
//规则验证
// var reg = /a\s/; //a字符后是否包含空白字符
// console.log(reg.test('helloa '));
// var reg = /a\s[0-9]/; //是否包含数字字符
// console.log(reg.test(hea 011'))
// var reg = /a\s\d\w/i;//匹配任何字符 数字、字母、下划线
// console.log(reg.test('hela 8888o'));
//量词
// var reg = /a\s\d[3]\w/i;//d[3]表示连续出现三个数字
// console.log(reg.test('hele 7768_lo'));
var reg = /a\s\d[3,]\w/i;
console.log(reg.test('hele 7768_lo'));
</script>
</head>
<body>
</body>
</html>
案例33
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
table tr td:first-child{
text-align: right;
}
.error{
font-size: 12px;
color: red;
}
.OK{
color: green;
}
</style>
<script>
function checkUsername() {
//用户名只能由字母、数字、下划线、横线、中文组成,且只能以数字或字母开头而结尾,长度为6-16位
var username = $("username").value;
var reg = /^[\da-z][\u4E00-\u9FA5\w-]{4,12}[\da-z]$/i;
if(!reg.test(username)){
$("usernameInFo").innerText="用户名只能由字母、数字、下划线、横线、中文组成,且只能以数字或字母开头而结尾,长度为6-16位";
$("usernameInFo").className="error";
return false;
}else{
$("usernameInFo").innerText="OK!";
$("usernameInFo").className="OK";
return true;
}
}
function checkPassword() {
//密码只能由数字、字母组成,长度为6-10位
var password = $("password").value;
var reg = /^[\da-z]{6,10}$/;
if(!reg.test(password)){
$("passwordInFo").innerText="密码只能由数字、字母组成,长度为6-10位";
$("passwordInFo").className="error";
return false;
}else {
$("passwordInFo").innerText="OK!";
$("passwordInFo").className="OK";
return true;
}
}
function checkRepassword() {
//两次输入的密码必须相同
var password = $("password").value;
var repassword = $("repassword").value;
if(password!=repassword){
$("repasswordInFo").innerText="两次输入的密码必须相同";
$("repasswordInFo").className="error";
return false;
}else{
$("repasswordInFo").innerText="OK!";
$("repasswordInFo").className="OK";
return true;
}
}
function checkBirthday() {
var birthday = $("birthday").value;
var reg = /^\d{4}-\d{1,2}-\d{1,2}$/;
if(!reg.test(birthday)){
$("birthdayInFo").innerText = "输入格式不正确";
$("birthdayInFo").className = "error";
return false;
}else{
$("birthdayInFo").innerText = "OK!";
$("birthdayInFo").className = "OK";
return true;
}
}
function checkPhone() {
var phone = $("phone").value;
var reg = /^1\d{10}$/;
if(!reg.test(phone)){
$("phoneInFo").innerText = "输入格式不正确";
$("phoneInFo").className = "error";
return false;
}else{
$("phoneInFo").innerText = "OK!";
$("phoneInFo").className = "OK";
return true;
}
}
function checkMail() {
var mail = $("mail").value;
var reg = /^\w+@\w+(\.[a-z]{2,3}){1,2}$/; // + 1个或多个 点号要转义 \.
if(!reg.test(mail)){
$("mailInFo").innerText = "输入格式不正确";
$("mailInFo").className = "error";
return false;
}else {
$("mailInFo").innerText = "OK!";
$("mailInFo").className = "OK";
return true;
}
}
function checkInput() {
console.log(111);
return checkUsername()&&checkPassword()&&checkRepassword()&&checkBirthday()&&checkPhone()&&checkMail();
}
//身份证 15位 18位(x)
// var reg = /^[1-9]\d{14}(\d{2}[\dx])?/i; //? 0个或多个 最后四位可有可无
function $(id) {
return document.getElementById(id);
}
</script>
</head>
<body>
<form action="sucess.html" onsubmit="return checkInput()">
<h2>用户注册</h2>
<table>
<tr>
<td>用户名:</td>
<td>
<input type="text" name="username" id="username" placeholder="请输入用户名" onblur="checkUsername()">
<span id="usernameInFo"></span>
</td>
</tr>
<tr>
<td>密码:</td>
<td>
<input type="password" name="password" id="password" placeholder="请输入密码" onblur="checkPassword()">
<span id="passwordInFo"></span>
</td>
</tr>
<tr>
<td>确认密码:</td>
<td>
<input type="password" name="repassword" id="repassword" placeholder="请再次输入密码" onblur="checkRepassword()">
<span id="repasswordInFo"></span>
</td>
</tr>
<tr>
<td>出生日期:</td>
<td>
<input type="text" name="birthday" id="birthday" placeholder="请输入出生日期" onblur="checkBirthday()">
<span id="birthdayInFo"></span>
</td>
</tr>
<tr>
<td>手机号:</td>
<td>
<input type="text" name="phone" id="phone" placeholder="请输入手机号" onblur="checkPhone()">
<span id="phoneInFo"></span>
</td>
</tr>
<tr>
<td>邮箱:</td>
<td>
<input type="text" name="mail" id="mail" placeholder="请输入邮箱" onblur="checkMail()">
<span id="mailInFo"></span>
</td>
</tr>
<tr>
<td colspan="2" style="text-align: left">
<input type="submit" value="注册">
<input type="reset" value="重置">
</td>
</tr>
</table>
</form>
</body>
</html>