Loading

JavaScript代码笔记

Javascript

使用js的三个方式

内嵌js、script代码块、外部引用js

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>Title</title>
   <script type="text/javascript">
       alert('head hello')
   </script>
   <script src="1.js" type="text/javascript"></script>
</head>
<body onload="alert('hello')">

</body>
</html>

注释

双斜杠 // 或 /* 与 */ 之间的代码被视为注释

输出

  • alert()

  • document.write()

    在 HTML 文档完全加载后使用 document.write()删除所有已有的 HTML

    <!DOCTYPE html>
    <html>
    <body>

    <h1>我的第一张网页</h1>

    <p>我的第一个段落</p>

    <button onclick="document.write(5 + 6)">试一试</button>

    </body>
    </html>
  • innerHTML()

  • console.log()

变量

JavaScript 变量是存储数据值的容器。

let age = 1; let departmentName = "Program";

错误:let dn = "sale"; let n1 = "sale"; let 1n = "sale";

可以包含英文字母+数字+下划线+$,不能以数字开头,建议以英文字母开头。

不要用拼音命名变量,不要用生僻的英文单词命名

let定义是局部变量,范围是以大括号为界。var局部变量,和let一样,区别是有变量提升现象。

<script>
   function f() {
       let age = 1;
       console.log('age=' + age)
  }

   //报错
   // console.log('age=' + age)

   f();

   function f1() {
       var username = 'zhangshan';
       console.log('name=' + username);
  }

   f1();
   //alt+shift+down
   //报错
   // console.log('name=' + username);
</script>
//报错
/*console.log('age=' + age);
let age = 1;*/
//var的提升现象
console.log('age=' + age);
var age = 1;
const MONEY = 10000;
//常量的值不能改变报错
// alert(MONEY++);

数据类型

原始数据

  • string

  • number

  • boolean

  • undefined

复杂数据

  • function

  • object

数组(在 JavaScript 中数组属于对象)

Undefined:没有值的变量,其值是 undefined。typeof 也返回 undefined。

Null : object

布尔类型Boolean:boolean

数值类型Number:number

字符串String:string

对象:object

函数:function

Undefined 与 Null 的区别

  • Undefined 与 null 的值相等,但类型不相等:

  • typeof, JS中if判断时,null和undefined为false ,数字0也是false

通过指定表示未找到相应元素时也是false if(document.getElementById('xx')){}

<script>
   let age = 1;
   let username = "admin";
   let adult = true;
   let money = null;
   let girlFriend;
   document.write('age: ' + typeof age + "     ;");
   document.write('username: ' + typeof username + "     ;");
   document.write('brithday: ' + typeof brithday + "     ;");
   document.write('money: ' + typeof money + "     ;");
   document.write('girlFriend: ' + typeof girlFriend + "     ;");
   //age: number username: string brithday: object money: object girlFriend: undefined
</script>

if条件判断时,true 、1是真可以执行if语句块内的代码

null、undefined、0、-1再条件判断里是假的

<script>
   let adult = true
   if (adult) {
       document.write("true");
  } else {
       document.write("false")
  }
   let money = null;
   //JS中把空当成false
   if (money) {
       document.write("1000$");
  } else {
       document.write("10000000$")
  }
   let girlFriend;
   if (girlFriend) {//undefined 也是false
       document.write("有女朋友");
  } else {
       document.write("没有")
  }

   let age = 0;
   if (age) {//0,-1也是false 1的时候为true
       document.write("ok");
  } else {
       document.write("no ok")
  }
</script>

双等和三等的判断

<script>
   let age = 1;
   if (age == 1) {
       alert("age is Number 1 ");//ok
  }
   if (age == "1") {
       alert("age is string '1' ");//ok
  }
   //=== 不仅内容要相等,类型也要相等
   if (age === "1") {
       alert("equals");
  } else {
       alert("no equals")
  }
</script>

总结:

  • 基本数据类型(Number,Boolean,String ,Null,undefined)

  • typeof运算符判断类型

  • if判断对于数字0,,-1,null, undefined,返回内容任一项不等返回false

isNaN()函数:是数字返回false,不是数字返回true

  • infinite是一个数字

  • age = "1";//他是一个字符串也是一个数字

<script>
   // alert(1/0);//infinity
   // alert(typeof Infinity);//类型number
   // is not a number() 函数 isNaN()
   let age = 1;
  /* alert(isNaN(age));//false
  age = "1";//他是一个字符串也是一个数字
  alert(isNaN(age))//false
  age = "a";
  alert(isNaN(age));//true*/
   age = Infinity;//是一个数字
   alert(isNaN(age));//false
</script>

number的一些方法

  • parseInt,parseFloat,toFixed

Number

math

document.write(Math.ceil(1.1));//向上取整为2
document.write(Math.ceil(-1.1));//向上取整-1 可以理解为ceil是向大数取整
document.write(Math.floor(1.1));//1
document.write(Math.floor(-1.1));//-2 floor可以理解为向小数取整
document.write(Math.trunc(-1.1));//trunc表示截断,断开小数点之后的数
//正数的四舍五入是正常的 负数的四舍五入是-0.6近-1,-0.5近0
document.write(Math.round(-0.5));
document.write(Math.round(-0.6));
document.write(Math.round(1.4));
document.write(Math.round(1.5));

String字符串

面试题:substr(起始位置,长度)和substring(起始位置,结束位置)的区别

substr()和substring()都可以进行字符串的截取

substr(起始位置,长度)

substring(起始位置,结束位置):不包括结束索引

<script>
let username = 'abc123.www.sohu.com,abc123.www.163.com,ychs公司';
console.log('dot length='+username.length);
console.log('dot indexof='+ username.indexOf('.'));
//第二个参数表示从下标为7的数组元素开始匹配
console.log('dot indexof='+ username.indexOf('.',7));
console.log('dot lastIndexOf='+ username.lastIndexOf('.'));
//search里面要写正则表达式。\\表示转义字符
console.log('dot search='+ username.search('\\.'));
//类似于切片访问,下面三个函数方法类似[0,6]
console.log('dot slice='+ username.slice(0,6));
console.log('dot substring='+ username.substring(0,6));
console.log('dot substr='+ username.substr(0,6));
//小写的abc替换为大写的ABC
console.log('dot replace='+ username.replace('abc','ABC'));
//正则替换所有
console.log('dot replace='+ username.replace(/abc/g,'ABC'));
console.log('dot toUpperCase='+ username.toUpperCase());
//该函数返回的是一个数组对象
console.log('dot split='+ username.split(',').length);
console.log('dot charAt='+ username.charAt(1));//字符输出
console.log('dot charCodeAt='+ username.charCodeAt(43));//数组下标为43的unicode编码
console.log('dot charCodeAt='+ username.charCodeAt(44));
console.log('dot trim='+ " 123 ".trim().length);//3
</script>

闭包(面试点)

函数中的函数(在一个函数中定义另一个函数,后者在前者内部)

闭包就是能够读取其他函数内部变量的函数。例如在javascript中,只有函数内部的子函数才能读取局部变量所以闭包可以理解成“定义在一个函数内部的函数。

在本质上,闭包是将函数内部和函数外部连接起来的桥梁。

优点:解决了一个问题,函数外部读取函数内部局部变量

缺点:1. 闭包所在的外部函数执行完后,它的局部变量无法自动回收,会带来内存泄漏(IE),占用大量内存无法释放。2. 闭包可以改变外部函数的局部变量,使用时需要注意

// 闭包就是能够读取其他函数内部变量的函数。
function fout() {
//局部变量
let count = 0;
//下面的函数是闭包,局部函数的外部调用
return function fin() {
alert(++count);
}
}
//fn指向了fout内部的函数
let fn = fout();
fn();//1
fn();//2
fn();//3

prototype

多用于方法,资源优化,使得每个对象不会占用太多的内存资源

函数(作为普通函数,类)

JavaScript 函数是被设计为执行特定任务的代码块。

函数调用

函数中的代码将在其他代码调用该函数时执行:

  • 当事件发生时(当用户点击按钮时)

  • 当 JavaScript 代码调用时

  • 自动的(自调用)

function f(){},switch语句

function f(num1, num2,opt) {
switch (opt) {
case '+':
return num1 + num2;
case '-':
return num1 - num2;
case '*':
return num1 * num2;
case '/':
return num1 / num2;
default:
return num1 + num2;
}
}
//函数传参
let num = f(1, 2,'*');
console.log(num);
num = f(1, 0,'/');
console.log(num);//鹰飞你提

函数当作类来使用

function f(num1, num2,opt) {
//this是当前调用本函数的对象。
console.log('this=' + this);
switch (opt) {
case '+':
return num1 + num2;
case '-':
return num1 - num2;
case '*':
return num1 * num2;
case '/':
return num1 / num2;
default:
return num1 + num2;
}
}
//函数传参
let num = f(1, 2,'*');
console.log(num);
num = f(1, 0,'/');
console.log(num);//鹰飞你提

//定义一个类 Java:class
function Calc(brand,manufacturers) {
//类内部,this指向了对象
this.brand = brand;
this.manufacturers = manufacturers;
this.work = f;
}

//创建出一个对象,calc这个变量就指向了这个对象
let calc = new Calc('suandekuai', 'Huawei');
console.log(calc.brand);
console.log(calc.manufacturers);
let result = calc.work(1, 2, '-');
console.log(result);

定义一个苹果类

<script>
function Fruit(name, price) {
this.name = name;
this.price = price;
this.sale = function (weight) {
return this.price * weight;
}
}

let apple = new Fruit('红富士', 5);
let money = apple.sale(4);
console.log(money + "元")
let peach = new Fruit();
peach.name = '大久保';
peach.price = 3;
money = peach.sale(5);
console.log(money + "元");
</script>

定义一个类:人

<script>
function f() {
//谁调用它,this指针指向的就是谁
console.log(this)
console.log('my name is:' + this.names + 'age is ' + this.age);
}
//定义一个类:人
function Person(names,age,gender) {
//属性
this.names = names;
this.age = age;
this.gender = gender;
this.introduce = f;
}
let p1 = new Person('马厉害',18,'男')
console.log(p1.names + "-" + p1.age + "-" + p1.gender);
//这里person的对象p1间接调用f这时this指的是p1这个物理地址
p1.introduce();
window.f();
</script>

局部变量全局变量

  • 通过 var 关键词定义的全局变量属于 window 对象

  • 通过 let 关键词定义的全局变量不属于 window 对象

//全局变量
let name = "globalName";
let age = 100;
function f() {
let name = "localName";
//局部变量
console.log(name);
console.log(age);
}
f();
console.log(name);

引用类型

数组

存储一组数组,通过连续的下标来访问数组元素,下标(索引)从0开始,数组的长度不固定,数组的数据类型不固定。

数组的初始化

  • [x,x,x]

  • new Array()

  • string.split

let arr = [1, 2, 3];
console.log(arr.length)
console.log(arr[0]);
console.log(arr[1]);
console.log(arr[2]);
arr[0] = 'a';
arr[1] = new Date();
console.log('改变值后的0下标数组='+arr[0]);
console.log('改变值后的1下标数组='+arr[1]);

for (let i = 0; i < arr.length; i++) {
console.log('循环输出数组'+arr[i]);
}

pop()后弹、push()后加

let arr = new Array();
console.log(arr.length);//数组默认长度是0
for (let i = 0; i < 5; i++) {
arr[i] = i;//直接复制
}
console.log('赋值后=' + arr.length);
let item = arr.pop();
console.log('dot pop= ' + arr.length);//弹出数据后数组长度变短
console.log(arr)

arr.push(4);
console.log(arr);

shift()前弹unshift()前加一个数组和join()

//往数组里面加一个分割符生成字符串
let str = arr.join();
console.log(str);
str = arr.join('-');//生成一个以‘-’为分隔符的数组字符串
console.log(str);
//前弹一个数组元素
item = arr.shift();
console.log('item = ' + item);
console.log('arr = ' + arr);
arr.unshift(0);
console.log(arr)

切片访问数组slice

console.log('arr = ' + arr.slice(1, 3));

数组排序

arr = arr.sort();
console.log('arr顺序排序后(从小到大) = ' + arr);
arr = arr.reverse();
console.log('arr倒序排列后(从大到小) = ' + arr);

对象

可以通过new类创建对象

//构造器定义一个类 Java:class
function Calc(brand,manufacturers) {
//类内部,this指向了对象
this.brand = brand;
this.manufacturers = manufacturers;
}

//创建出一个对象,calc这个变量就指向了这个对象
let calc = new Calc('suandekuai', 'Huawei');
console.log(calc.brand);
console.log(calc.manufacturers);

JSON对象

  • JSON 对象被花括号 {} 包围。

  • JSON 对象以键/值对书写。

  • 键必须是字符串,值必须是有效的 JSON 数据类型(字符串、数字、对象、数组、布尔或 null)。

  • 键和值由冒号分隔。

  • 每个键/值对由逗号分隔。

//键值对的方式定义属性和方法
let person = {
firstName: 'zhang',
lastName: 'san',
fullName: function () {
return this.firstName + this.lastName;
}
}
let fullName = person.fullName();
console.log(fullName);

日期

new XX(),XX()就是构造函数 ,new Date(),Date()就是构造函数,是一个无参的。

<script>
let today = new Date();
console.log(today);

// javascript记录的时间从下面day1开始
let day1 = new Date(0);
console.log(day1);
// 从day1开始加括号内的毫秒等于多少日,下面的时间加了一天
let day2 = new Date(24 * 3600 * 1000);
console.log(day2);
// 下面的时间加了一个月
let day3 = new Date(31 * 24 * 3600 * 1000);
console.log(day3);

// 2000年距离1970年差多少毫秒
let day4 = new Date("Jan 01 2000 00:00:00");
console.log(day4);
console.log(day4.getTime());

// 自定义时间
let day5 = new Date(2001, 0, 2, 7, 35, 35, 33);
console.log(day5);

// 分别获取当前时间的各个单位
let year = today.getFullYear();
let month = today.getMonth() + 1;
let day = today.getDate();
let hours = today.getHours();
let min = today.getMinutes();
let sec = today.getSeconds();
let mill = today.getMilliseconds();
console.log(year + "-" + month + "-" + day + "-" + hours + "-" + min + "-" + sec + "-" + mill)
</script>
<script>
let date = new Date();
// 为了格式化输出日期,我们在跟类里写一个format方法用于格式化我们获取的时间对象
Date.prototype.format= function(){
return this.getFullYear() + "-"+ (this.getMonth()+1) + "-" + this.getDate() + "-"+ this.getHours() + "-" + this.getMinutes()
}
console.log(date.format());

//明天的日期
// getTime()获取当前时间
let date2 = new Date(date.getTime() + 24 * 3600 * 1000);

console.log(date2.format())
</script>

this是什么?

JavaScript this 关键词指的是它所属的对象。

它拥有不同的值,具体取决于它的使用位置:

  • 在方法中,this 指的是所有者对象。

  • 单独的情况下,this 指的是全局对象。

  • 在函数中,this 指的是全局对象。

  • 在函数中,严格模式下,this 是 undefined。

  • 在事件中,this 指的是接收事件的元素。

像 call() 和 apply() 这样的方法可以将 this 引用到任何对象。

//this是当前调用本函数的对象。
console.log('this=' + this);

call()方法的使用

<script>
let person = {
firstName: 'zhang',
lastName: 'san',
fullName: function () {
return this.firstName + this.lastName;
}
}
let fullName = person.fullName();
console.log(fullName);

// JavaScript中的call()
// 原理:call改变了this的指向
// 作用借别的方法来使用,借别的内容来使用
let p1 = {
firstName: 'li',
lastName: 'si'
}
//理解:对象person方法调用自己的fullName方法,并把fullName方法里面的this指向的对象改变成了p1对象
fullName = person.fullName.call(p1);
console.log(fullName);

let p2 = {firstName: 'wang', lastName: 'wu'};
fullName = person.fullName.call(p2);
console.log(fullName);
// 传参
// 给person增加方法
person.fullName2 = function (firstName, lastName) {
return firstName + lastName;
}
let p3 = {}
fullName = person.fullName2.call(p3, '赵', '六');
console.log(fullName);
</script>

apply()方法的使用

let person = {
fullName: function () {
return this.firstName + this.lastName;
},
fullName2: function (firstName,lastName) {
return firstName + lastName;
}
}
let p1 = {
firstName: '赵',
lastName: '一'
}
//apply和call区别在于apply第二个参数是Array,而call是将一个个传入
fullName = person.fullName.apply(p1);
console.log(fullName);
fullName = person.fullName2.apply(p1, ['钱', '二']);
console.log(fullName);

math()函数,和call、apply方法的调用

//正常的max方法
let max = Math.max(6, 2, 100, 3)
console.log(max);

//使用call调用max方法
max = Math.max.call(null, 6, 22, 1, 3);
console.log(max);

//使用apply方法
let arr = [66, 2, 1, 3];
max = Math.max.apply(null, arr);
console.log(max);

JSON

JSON对象,JSON字符串

页面向后台传递数据JSON有两种格式,一种是JSON字符串,把JSON对象通过JSON.stringify()传递,原因是取决于后台只能识别JSON字符串。

如果后台只能识别JSON对象,页面需要传递JSON对象。

后台返回给页面一个JSON字符串(只能是字符串,后台技术规定的),页面拿到JSON字符串后台不好处理,JSON.parse()转换成对象就可以通过对象.XX来获取数据

<script>
// 定义一个JSON对象
let apple = {id:1,name:"apple1", price: 1}
console.log(apple);//apple是一个对象
console.log(JSON.stringify(apple));//将其变为JSON对象

// 模拟后台给的相应
let appleStr = JSON.stringify(apple);//将对象变成JSON字符串
let result = JSON.parse(appleStr);//优化,使得访问和解析更加方便
console.log("id=" + result.id + "name:" + result.name + "price:" + result.price);
</script>

DOM

Document 对象是 Window 对象的一部分,可通过 window.document 属性对其进行访问。

document object model 文档对象模型,浏览器会把HTML文档当作一个对象,放在程序中进行处理。document

通过document可以获取页面上元素的值或属性等,可以动态增加页面上的元素或移除元素,可以给元素动态赋值,可以改变元素的外观。

function checkAll(elem) {
// xx.checked表示复选框是否被选中了,选中返回true,否则false
// alert(elem.checked)
let cbxSons = document.getElementsByName("cbxSon");
for (let i = 0; i < cbxSons.length; i++) {
// 所有复选框的选择状态和全选的复选框保持一致
cbxSons[i].checked = elem.checked;// 将true或false赋值给所有的
}
}

动态添加下拉列表

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
window.onload = function () {
// 创建一个div
let div = document.createElement('div');
div.style.height = '50px';
div.style.border = '1px solid red';
// 把div对象加载到页面中
// 找到body
// let body = document.getElementsByTagName("body")[0];//第一种方法

let body = document.body;//第二种方法

// 给其添加一个子元素div
body.appendChild(div);

let btn = document.getElementsByTagName("button")[0];
btn.onclick = function () {
let value = document.forms[0].collageOptValue.value;
let text = document.forms[0].collageOptText.value;
let college = document.forms[0].college;
//第二种方式动态添加下拉列表
let opt = document.createElement("option");
opt.value = value;
opt.text = text;
college.appendChild(opt);
//第一种方式动态添加下拉列表
/*college.length++;
college.options[college.options.length-1].value = value;
college.options[college.options.length-1].text = text;*/


document.forms[0].collageOptValue.value = '';
document.forms[0].collageOptText.value = '';
/*let opts = college.options;
college.insertBefore(option,"<option value='" + value + "'>" + text + "</option>");
// alert(value+text)*/
};
};

</script>
</head>
<body>
<form>
下拉框的值:<input type="text" name="collageOptValue">
下拉框显示:<input type="text" name="collageOptText">
<button type="button">增加</button>
<select name="college">
<option value=''>-请选择-</option>
</select>
</form>
</body>
</html>

选择器

获取页面元素可以用指定的标识入:id , class, name , tagName等

function init() {
// JavaScript代码先执行,后面HTML代码后执行
let div1 = document.getElementById("div1");
console.log(div1);

// 根据classname获取,获取的是数组
let c1 = document.getElementsByClassName("c1");
console.log(c1);
for (let i = 0; i < c1.length; i++) {
console.log(c1[i]);
}
// 根据标签名获取,获取的是数组
let divs = document.getElementsByTagName("div");
for (let i = 0; i < divs.length; i++) {
console.log(divs[i]);
}
}

事件

单击,双击,鼠标在

DOM和事件紧密联系。所有的事件以on开头,如:onclick单击

dbclick,change,blur,focus,mouse(),keyboard()

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
// onmouseenter判断鼠标进入元素比较直观
function mouseenter() {
console.log("enter in div")
}
// onmouseleave表示鼠标离开了元素
function mouseleave() {
console.log("leave out div")
}
// onmouseover如果定义在父元素,只要经过一个子元素,就会被触发一次
function mouseover() {
// console.log("鼠标在元素上");
}
// onmouseout 如果定义在父元素,只要离开一个子元素,就会被触发一次
function mouseout() {
// console.log("鼠标出了元素");
}
</script>
</head>
<body>
<div style="border: 1px solid green;width: 60vw" onmouseenter="mouseenter();" onmouseleave="mouseleave();"
onmouseover="mouseover();" onmouseout="mouseout();">
<div style="border: 1px solid blue;width: 30vw">
<span style="border: 1px solid red;padding: 0 10px">1</span>
</div>
</div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
function down() {
console.log("down");
}
// 特殊的符号键,空格,enter会触发press
function press() {
console.log("press")
}
function up() {
console.log("up")
}
</script>
</head>
<body>
<input type="text" onkeydown="down();" onkeypress="press();" onkeyup="up();">
</body>
</html>

计算器

step1

做边框

step2

做外观

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
* {
margin: 0;
padding: 0;
}
body {
width: 100vw;
height: 100vh;
/*border: 1px solid red;*/
}
#divCalc {
border: 1px solid gray;
width: 30vw;
height: 70vh;
/*将div的左上角顶点移到中间*/
position: relative;/*没有用到父元素的用absolute*/
left: 50%;
top: 50%;
/*position: relative;!*没有用到父元素的用absolute*!
left: 50vw;
top: 50vh;*/
/*将div中心移到屏幕中心*/
margin-left: -15vw;
margin-top: -35vh;
}
#divResult {
text-align: center;
/*border: 1px solid red;*/

line-height: 14vh;
height: 20%;
}
#divNumber,#divOpt {
float: left;
border: 1px solid black;
height: 80%;
}
#divNumber {
width: 75%;
}
#divOpt {
width: 23%;
}
.btnNum {
margin-left: 2vh;
width: 5vw;
height: 12vh;
margin-bottom: 2vh;
}
</style>
</head>
<body>
<div id="divCalc">
<div id="divResult">0</div>
<div id="divNumber">
<button class="btnNum">7</button>
<button class="btnNum">8</button>
<button class="btnNum">9</button>
<button class="btnNum">4</button>
<button class="btnNum">5</button>
<button class="btnNum">6</button>
<button class="btnNum">1</button>
<button class="btnNum">2</button>
<button class="btnNum">3</button>
<button class="btnNum">-</button>
<button class="btnNum">0</button>
<button class="btnNum">+</button>
</div>
<div id="divOpt">
<button class="btnNum">/</button>
<button class="btnNum">*</button>
<button class="btnNum">cls</button>
<button class="btnNum">=</button>
</div>
</div>
</body>
</html>

step3

做交互

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
* {
margin: 0;
padding: 0;
}

body {
width: 100vw;
height: 100vh;
/*border: 1px solid red;*/
}

#divCalc {
border: 1px solid gray;
width: 30vw;
height: 70vh;
/*将div的左上角顶点移到中间*/
position: relative; /*没有用到父元素的用absolute*/
left: 50%;
top: 50%;
/*position: relative;!*没有用到父元素的用absolute*!
left: 50vw;
top: 50vh;*/
/*将div中心移到屏幕中心*/
margin-left: -15vw;
margin-top: -35vh;
}

#divResult {
text-align: center;
/*border: 1px solid red;*/

line-height: 14vh;
height: 20%;
}

#divNumber, #divOpt {
float: left;
border: 1px solid black;
height: 80%;
}

#divNumber {
width: 75%;
}

#divOpt {
width: 23%;
}

.btn {
margin-left: 2vh;
width: 5vw;
height: 12vh;
margin-bottom: 2vh;
}

.btnOpt {
height: 5vh;
}

#divOpt button:last-child {

}

#divOpt button:first-child {

}
</style>
<script>
let num1, num2, numResult, opt;

function setNumber(elem) {
if (opt) {
if (num2) {
num2 += elem.innerText;
} else {
num2 = elem.innerText;
}
document.getElementById("divResult").innerText = num2;
} else {
if (num1) {
num1 += elem.innerText;
} else {
num1 = elem.innerText;
}
document.getElementById("divResult").innerText = num1;
}
}

function setOpt(elem) {
let o = elem.innerText;
if (o === '=') {
if (opt === '+') {
numResult = parseInt(num1) + parseInt(num2);
} else if (opt === '-') {
numResult = parseInt(num1) - parseInt(num2);
} else if (opt === '*') {
numResult = parseInt(num1) * parseInt(num2);
} else if (opt === '/') {
if (num2 === '0') {
numResult = 'Infinity';
} else {
numResult = parseInt(num1) / parseInt(num2);
}
}
document.getElementById('divResult').innerText = numResult;
} else if (o === 'C') {
num1 = num2 = numResult = opt = null;
document.getElementById('divResult').innerText = '0';
} else if (o === '<') {
if (opt) {
if (num2.length === 1) {
num2 = '0';
document.getElementById('divResult').innerText = num2;
} else {
num2 = num2.substr(0, num2.length - 1);
document.getElementById('divResult').innerText = num2;
}
} else {
if (num1.length === 1) {
num1 = '0';
document.getElementById('divResult').innerText = num1;
} else {
num1 = num1.substr(0, num1.length - 1);
document.getElementById('divResult').innerText = num1;
}
}
} else {
opt = o;
}
}
</script>
</head>
<body>
<div id="divCalc">
<div id="divResult">0</div>
<div id="divNumber">
<button class="btn" onclick="setNumber(this)">7</button>
<button class="btn" onclick="setNumber(this)">8</button>
<button class="btn" onclick="setNumber(this)">9</button>
<button class="btn" onclick="setNumber(this)">4</button>
<button class="btn" onclick="setNumber(this)">5</button>
<button class="btn" onclick="setNumber(this)">6</button>
<button class="btn" onclick="setNumber(this)">1</button>
<button class="btn" onclick="setNumber(this)">2</button>
<button class="btn" onclick="setNumber(this)">3</button>
<button class="btn" onclick="setNumber(this)">-</button>
<button class="btn" onclick="setNumber(this)">0</button>
<button class="btn" onclick="setNumber(this)">+</button>
</div>
<div id="divOpt">
<button class="btn btnOpt" onclick="setOpt(this)">C</button>
<button class="btn btnOpt" onclick="setOpt(this)">&lt;</button>
<button class="btn btnOpt" onclick="setOpt(this)">/</button>
<button class="btn btnOpt" onclick="setOpt(this)">*</button>
<button class="btn btnOpt" onclick="setOpt(this)">-</button>
<button class="btn btnOpt" onclick="setOpt(this)">+</button>
<button class="btn btnOpt" onclick="setOpt(this)">=</button>
</div>
</div>
</body>
</html>

对话

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
let salary = Math.random()*1000 + 4000;
salary = Math.round(salary)
console.log("salary=" + salary);
function guess(elem) {
let value = elem.value;
if (value == salary) {
document.getElementsByTagName("span")[0].innerText = '你猜对了';
}else if (value > salary) {
document.getElementsByTagName("span")[0].innerText = '大了';
} else {
document.getElementsByTagName("span")[0].innerText = '小了';
}
}
</script>
</head>
<body>
<label>张三:听说,发工资了,你发了多少?</label><br>
<label>李四:你猜!</label><br>
<label>张三:</label><input onblur="guess(this)"><br>
<label>李四:</label><span></span>
</body>
</html>

正则

==书写逻辑==第一步我要写什么第二步我能写几个

保证数据有效性:非空,格式正确

表达式: let reg = /xxx/; reg.test(待检查的内容) true/false

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
function check() {
let inputNode = document.getElementById("input1");

let reg = /tom/;// 校验text文本中有没有包含tom这个单词

reg = /^tom$/;// 只能是tom

reg = /^[ta]$/;//[]代表可以选择的内容,只能校验一位

reg = /^[0-9]$/;//[]代表可以选择的内容,只能校验一位

reg = /^[0-9][0-9][0-9]$/;//[]代表可以选择的内容,只能校验一位

reg = /^[0-9]{1,3}$/;//[]代表可以选择的内容,{}代表能写个数的范围,能校验1-3位

reg = /^[0-9]{10}$/;//[]代表可以选择的内容,{}代表能写个数的范围,只能校验10位

reg = /^[0-9]{1,}$/;//{1,}代表最少校验一位

reg = /^[0-9]?$/;// ?代表是可有可无,最多一个

reg = /^[0-9]+$/;// +至少一位

reg = /^[0-9]*$/;// 不管是多少位,只能是数字

// 可以是字母和数字和下滑线---------------------
reg = /^[a-zA-Z0-9_]{1,4}$/

reg = /^.{1,4}$/;//任意字符,1-4位校验

// 必须是小数
reg = /^[0-9]+\.[0-9]{1,2}$/;// \.表示小数“点”的转义

// 输入正确的数学运算
reg = /^[0-9]+\+[0-9]+=[0-9]+$/;

reg = /^\d$/;//【0-9】可以用\d表示


// 正确的ip地址
// 1.1.1.1 12.12.12.12 125.234.0.1 01错的
reg = /^(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])$/

// 正则校验
if (reg.test(inputNode.value)) {
alert("ok");
} else {
alert("no")
}
}
</script>
</head>
<body>
<input type="text" id="input1">
<input type="button" onclick="check();" value="检测text文本框">
</body>
</html>

替换和正则的参数

let reg = /^[\u4e00-\u9fa5]{2,4}$/;
console.log(reg.test(""));

// g Global/ i Ignore
reg = /0/g;
// i 可以表示忽略大小写
// g 表示全局替换
console.log("a01234567890A".replace(reg, "零").replace(/a/ig,"b"));

转义字符\d, \D, \s, \S

// \d表示数字
reg = /^\d$/;
console.log(reg.test(1));
console.log(reg.test('a'));
// \D表示非数字
reg = /^\D$/;
console.log(reg.test(1));
console.log(reg.test('a'));
// \s表示空格
reg = /^\s+$/;
console.log(reg.test(" "));
console.log(reg.test(' '));
// \S表示非空格
reg = /^\S$/
console.log(reg.test(" "));
console.log(reg.test(' '));

\W ,\w

// \w表示:字母、数字、下划线
reg = /^\w+$/;
console.log(reg.test('abcABC123_'));//true
console.log(/^[a-zA-Z0-9_]+$/.test('abcABC123_'));// true
console.log(reg.test('abc中.'));// false
1
// \W非字母表示:除了字母数字下划线
reg = /^\W+$/;
console.log(reg.test('abcABC123_'));// false
console.log(reg.test('中'));// true

// /^\w\W+$/ 表示一切 和 /^.+$/差不多
reg = /^[\w\W]+$/;
console.log(reg.test("中华。 @#%、 。"));//true
console.log(/^.+$/.test("中华。 @#%、 。"));//true

数据有效性,表单校验,失去焦点校验

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>Title</title>
   <style>
       input {
           border: 1px solid lightblue;
      }
   </style>
   <script>
       // 定义正则来对input文本框输入内容校验
       // 定义正则只能输入字母、数字、下划线、4-8位
       let regUserName = /^\w{4,8}$/;
       let regPassword = /^\w{4,8}$/;

       //页面加载完成后执行
       window.onload = function () {
           // 1.通过name查找
           // let username = document.getElementsByName("username")[0];
           // 2.通过HTML元素查找 ,原理是该元素位于HTML里面的第几位
           let username = document.forms[1].username;
           let password = document.forms[1].password;//form[1].可以点id,点name,如果name值相同,采用数组访问
           // 3.通过HTML元素的name查找,[]内可以放id name属性查找
           // let username = document.forms["frm"].username;
           username.onblur = function () {
               check(username, regUserName);
          }
           // 绑定事件的监听 参数:事件类型,事件方法,。。。
           password.addEventListener('blur',function () {
               check(password, regPassword);
          },true)
           // 给表单绑定提交事件
           /*document.forms[1].onsubmit = function () {
              let resultUsername, resultPassword;
              resultUsername = check(document.forms[1].username, regUserName);
              resultPassword = check(document.forms[1].password, regPassword);
              // 若有一个为false则提交不成功
              return resultPassword && resultUsername;
          }*/
      };

       // 第二种页面调用js方式,通过HTML内嵌事件调用
       function fromSubmit() {
           let resultUsername, resultPassword;
           resultUsername = check(document.forms[1].username, regUserName);
           resultPassword = check(document.forms[1].password, regPassword);
           // 若有一个为false则提交不成功
           return resultPassword && resultUsername;
      }

       // 公共检查方法,谁都可以调用
       function check(element,regExp) {
           if (regExp.test(element.value)) {
               element.style.borderColor = 'lightblue';
               return true;
          } else {
               element.style.borderColor = 'red';
               return false;
          }
      };
   </script>
</head>
<body>
<!--form1-->
   <form action="" method="post" name="frm">
       <label>用户名:</label>
       <input type="text" name="username">
       <label>密码:</label>
       <input type="password" name="password">
       <input type="submit">
   </form>
<!--form2-->
   <form action="https://www.baidu.com" method="post" name="frm"  onsubmit="return fromSubmit()">
       <label>用户名:</label>
       <input type="text" name="username">
       <label>密码:</label>
       <input type="password" name="password">
       <input type="submit" value="提交">
   </form>
</body>
</html>

BOM

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>Title</title>
   <script>
       console.log(window);
       window.onload = function () {
           document.getElementsByTagName("button")[0].onclick = function () {
               //location的相关属性
               let hostname = Location.hostname;
               let protocol = location.protocol;
               let path = location.pathname;
               let prot = location.port;
               alert(protocol + '//' + hostname +':'+ prot + path);
               //指定浏览器地址,并且触发刷新的动作
               window.location.href = '3.html';
          }
      }
   </script>
</head>
<body>
   <button>3.html</button>
   <button type="button" onclick="history.forward()">前进</button>
</body>
</html>

轮播

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>Title</title>
   <style>
       .lamp {
           width: 50px;
           height: 50px;
           border: 1px solid lightblue;
           float: left;
           border-radius: 50%;
      }
       #clear {
           clear: both;
      }
   </style>
   <script>
       // 灯定时器
       let timerLamp;
       // 灯序号
       let indexLamp = 0;
       // 所有的灯
       let lamps;

       window.onload = function () {
           let btnStop = document.getElementById("btnStop");
           let btnStart = document.getElementById("btnStart");
           btnStop.disabled = true;
           btnStart.onclick = function () {
               this.disabled = true;
               btnStop.disabled = false;
               timerLamp = window.setInterval(lampShow, 1000);
          };
           btnStop.onclick = function () {
               this.disabled = true;
               btnStart.disabled = false;
               // 让定时器失效
               window.clearInterval(timerLamp);
          };
           // 初始化灯
           lamps = document.getElementsByClassName('lamp');
      }

       function lampShow() {
           // 所有的灯灭灯
           for (let i = 0; i < lamps.length; i++) {
               lamps[i].style.backgroundColor = 'white';
          }
           // 让灯亮起来
           lamps[indexLamp++].style.backgroundColor = 'red';
           /*if (indexLamp == 6) {
              indexLamp = 0;
          }*/
           // 数字零的滚动
           indexLamp %= 6;
      }

   </script>
</head>
<body>
   <div class="lamp"></div>
   <div class="lamp"></div>
   <div class="lamp"></div>
   <div class="lamp"></div>
   <div class="lamp"></div>
   <div class="lamp"></div>
   <div id="clear"></div>
   <div>
       <button id="btnStart" type="button">start</button>
       <button id="btnStop" type="button">stop</button>
   </div>
</body>
</html>
posted @ 2021-11-28 18:48  大聪明_小蓝  阅读(148)  评论(0)    收藏  举报