JavaScript_1

1.什么是JavaScript

JavaScript是世界上最流行的脚本语言

从构型到开发用了十天时间,与Java的关系就像雷锋和雷峰塔。

合格的后端人员,必须精通JavaScript

ECMCScript是JavaScript的一个标准,最新版本到了6,但大部分浏览器仅支持es5,所以开发环境中需要使用webPack打包成es5标准。


2.快速入门

2.1 引入JavaScript
  • 在html代码中直接书写(内部标签)

  • 单独建立JavaScript文件,在html中引入(外部引入)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    
<!-- 1.   script标签 ,写java代码,可放在head或body中-->
    <script>
       alert("hello"); //弹窗-->
    </script>
        
<!-- 2.   注意:script成对出现-->
    <script src="qj.js"></script>
    
<!-- 1.    其实不用显示定义type,也默认是javaScript-->
    <script type="text/javascript">

    </script>
</head>
<body>

</body>
</html>

2.2 基本语法入门
//1.定义变量  所有变量类型都为var
var num = 14;
//2.条件控制
if (num < 2) {
    alert("yes");
}else if (num > 10 && num < 50) {
    alert("no");
} else {
    alert("haha")
}
//3.JavaScript严格检查大小写

ES6后引入了新得声明类关键字let 和 const

const

  • 声明时就必须赋值,之后不可改变。保障内存地址不得改动。
  • 常量内存地址保存的是值,复合类型的数据内存地址中保存的是指针
  • 声明的作用域只在当前的块级中

let

  • 声明的作用域只在当前的块级中

控制台打印变量

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-aWM62OZt-1601040718595)(\pictures\image-20200720110209414.png)]


2.3 数据类型

数值、文本、图像、音频、视频

变量

var //默认全局变量

number

javaScript 不区分整数和小数,统称为number

123 //整数
12.3 //浮点数
1.23e3 //科学计数法
-12 //负数
NaN //not a number
Infinity //无限大

字符串

“abc”

‘abc’


布尔值

true false


逻辑运算

&& || !


比较运算

= 赋值
== 等于(只要值一样,结果就为true)
=== 绝对等于(类型一样,值一样,结果为true)常用

JS缺陷:

  • NaN与所有数值都不相等,包括自己
  • 只能通过 isNaN(NaN)方法 判断是否为Nan
  • 尽量避免使用浮点数进行运算,存在精度问题
if (Math.abs(1 / 3 - (1 - 2 / 3)) < 0.000000000001)
可使用这种方法判断两数是否相等

null和undefine

  • null 空
  • undefine 未定义

数组

var arr = [1,2,3.3,true,false,"adv"];  //推荐使用
var cars = new Array("Saab", "Volvo", "BMW");
不严谨的地方

数组下标越界时,会打印undefine


对象

对象是大括号,数组是中括号

//Person person = new Person(1,2,3,4);
var person = {
        name:"buyi", 
        age:9,
        tags:['js','java','web','...']
}

取对象的值

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Xz2Fxpz0-1601040718597)(G:\Java_learn\笔记文件\前端笔记\pictures\image-20200720120509370.png)]


2.4 严格检查模式
'use strict'
//预防JavaScript的随意性导致一些问题
//需要编译器支持ES6标准

3.数据类型

3.1 字符串
  1. 正常字符串使用单双引号包裹
  2. 特殊字符使用转义字符
\'
\"
\n
\t
\u2e2d Unicode编码
\x41   Ascll编码
  1. 多行字符串编写
var msg = `你好世界,
hello,World!
`; //tab键上方
  1. 模板字符串 ES6
let name = 'BuYi'
var msg = `你好世界,
hello,World!${name}
`;
console.log(msg);
  1. 字符串长度
console.log(student.length);
  1. 字符串的不可变性
console.log(student[1]);
但是不能给索引值赋值
  1. 大小写转换
//这里是方法,不是属性
student.toLowerCase();
student.toUpperCase();
  1. 获取字符下标
name.indexOf('b');
name.lastIndexOf('i');
  1. 截取字符串
name.substring(1);   // 从下标1到最后
name.substring(1,3); //   [)

3.2 数组

Array可以包换任意的数据类型

var arr = [1,2,3.3,true,false,"adv"];  //推荐使用
var cars = new Array("Saab", "Volvo", "BMW");
  1. 长度
arr.length
//给arr.length赋值可以改变数组大小,如果赋值小于当前数组长度,元素会丢失
  1. indexOf
arr= [1,2,3,4,5,6,'1'];
arr.indexOf('1') //6
arr.indexOf(1)   //0
  1. slice() 截取Array的一部分,返回一个新数组 [ )
arr.slice(1,3) ;
  1. push压入 , pop弹出
arr.push('a','3'); //压入到尾部
arr.push(); //弹出尾部一个元素
  1. unshift()压入, shift()弹出 头部
arr.unshift('a','3'); //压入到头部
arr.shift(); //弹出头部一个元素
  1. 排序sort()
arr.sort();
  1. 元素反转
arr.reverse();
  1. concat() 连接
arr.concat([1,2,3]); //返回一个新的数组,不会改变arr
  1. 打印拼接数组join
arr.join('-'); //使用特定字符串连接
//"1-2-3-4-5-6-1-1-2"
  1. 多维数组

3.3 对象
  1. 若干个键值对(键是字符串,值是任意对象)
var 对象名 = {
    属性名:属性值,
    属性名:属性值,
    属性名:属性值
}
var person = {
    name:"benbuyi",
    age: 19,
    email:"kougoxuan@qq.com"
}

JavaScript中的对象,都是以键值对的形式描述,属性之间逗号隔开,最后一个不加逗号(浏览器会不兼容)

  1. 使用一个不存在的对象属性不会报错,undefine

  2. 动态的删减属性

delete person.age
true
person.age
undefined
  1. 动态添加属性
person.age = 12
  1. 判断属性值是否在对象中
'score' in person //false
'toString' in person //true 继承
person.hasOwnProperty('toString') //判断一个属性是否为对象自身拥有

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-rl68okV2-1601040718598)(\pictures\image-20200720223110207.png)]


3.4 流程控制
if-else判断
while循环
do-while循环
for循环
for (let i = 0; i < 100; i++) {
    console.log(i);
}

var num = [1,3,4,5,6,76];
num.forEach(
    function (value) {
    console.log(num);
}
) //ES5.1

for (let n in num) {
    console.log(num[n]);
}//n为索引值 0-5

for (let n of num) {
    console.log(n);
}//n为num的值  ES6

3.5 Map和Set ES6

Map:键值对

//Map集合 类似python字典
var map = new Map([['tom',123],['ala',90],['janny',122]]);
var name = map.get('tom'); //取值
map.delete('ton');   //删除
map.set('admin',234);//添加

Set:无序不重复集合

var set = new Set([1,1,1,2,2,3,4,2]);//可以去重
set.add('1');   //添加
set.delete('1');//删除
set.has(1);    //是否包含

3.6 iterator ES6

专门用来迭代Map、Set、数组

var map = new Map([['tom',123],['ala',90],['janny',122]]);
for (let x of map) {
    console.log(x);
}

var set = new Set([1,1,1,2,2,3,4,2]);//可以去重
for (let number of set) {
    console.log(number);
}

for-in 漏洞

var arr = [1,3,4];
arr.name

4.函数

4.1 定义函数

定义方式一

public 返回值类型 函数名(){
	return 返回值;
}

function abs(x){
    if(x<0){
        return -x;
    }else{
        return x;
    }
}
一旦执行到return,代表函数结束,返回结果。
如果没有执行到return,函数也会返回结果 undefined

定义方式二

var abs = funciton(x){
    if(x<0){
        return -x;
    }else{
        return x;
    }
}

调用函数

abs(-10)  //10
abs(10)   //10

参数问题:JavaScript可以传入任意参数,也可以不传递参数。

如何规避不传参数问题

function abs(x){
    if (typeof x != 'number') {
        throw 'Not a Number';
    }
//手动抛出异常
    if(x<0){
        return -x;
    }else{
        return x;
    }
}

arguments

可以通过arguments获得传入参数的数组

function abs(x){
    for (var i = 0; i < arguments.length; i++) {
        console.log(arguments[i]);
    }

    if(x<0){
        return -x;
    }else{
        return x;
    }
}

问题:想要使用arguments首个参数之外的参数

rest ES6

获取除了已经定义的参数之外的所有参数 …

function aaa(x, y, ...rest) {
    console.log('x=>' + x);
    console.log('y=>' + y);
    console.log(rest)

}

4.2 变量作用域

var的变量作用域

  • 在函数体中声明,在函数体外不可以使用(想使用可以使用闭包)
  • 两个函数是同相同变量名,不冲突
function qj() {
    var x =1;
    x=x+1;
}
function ja() {
    var x = 1;
}

  • 内部函数可以访问外部函数成员,反之不行
function qj() {
    var x =1;
    function ja() {
    var y = x + 1; //没问题
    var x = 'A';   //没问题
}
    var z = y + 1; //报错
}

当内部函数变量和外部函数变量名相同时,以内部为准

javaScript中 函数查找变脸从自身变量开始,由内向外查找。

规范:将所有使用的变量都填写在头部,先定义,用的时候在赋值


全局变量
var x = 1;
function f() {
    console.log(x);
}
f();
console.log(x);
全局对象Windows
var x = 'www';
alert(x);
window.alert(x);//alert本身也是window对象的一个变量对象
alert(window.x); //默认所有全局变量,都自动绑定在window对象下

var old_alert = window.alert;
old_alert(x); //与alert等价

//甚至可以重新定义全局变量alert
window.alert = function () {

}//之后调用alert会失效

JavaScript 实际上只有一个全局作用域,任意变量(函数也会视为变量),假设没有在函数作用域范围找到,就会向外查找,如果在全局作用域都没找到,就会报错。

规范

由于所有的全局变量都会绑定到window上。如果引入不同的js文件,使用相同全局变量会冲突。需要想办法规避

唯一全局变量
//唯一全局变量,其实就是定义了一个对象,往里面放属性键值对
var Benbuyi = {};
//定义个人全局变量
Benbuyi.name = 'alal';
Benbuyi.add = function (a,b) {
    return a + b;
}

将自己的代码放在自己定义的唯一空间名字中,降低全局冲突。

jQuery也是这么做的 ,也可以用$代替jQuery

局部作用域 let ES6
function f() {
    for (let i = 0; i < 100; i++) {
        console.log(i);
    }
    console.log(i);//i is not defined
}
常量 ES6

约定:大写字符命名

  • 声明时就必须赋值,之后不可改变。保障内存地址不得改动。
  • 常量内存地址保存的是值,复合类型的数据内存地址中保存的是指针
  • 声明的作用域只在当前的块级中

4.3 方法

方法就是放在对象中的函数,对象只有两个东西:属性和方法

  • 调用方法一定要用括号
  • 调用属性不用括号
var Buyi = {
    name:'alan',
    birth:1999,
    //对象中的函数就是方法
    age: function () {
       var now =  new Date().getFullYear();//当前日期
       return now - this.birth;
    }
}

this默认指向调用它的对象

function getAge() {
    var now =  new Date().getFullYear();
    return now - this.birth;
}
var Buyi = {
    name:'alan',
    birth:1999,
    //对象中的函数就是方法
    age: getAge()
}

apply

在js中可以控制this的指向

第一个参数就是需要绑定的this变量,第二个参数是Array,表示函数本身的参数。

function getAge() {
    var now =  new Date().getFullYear();
    return now - this.birth;
}
var Buyi = {
    name:'alan',
    birth:1999,
    //对象中的函数就是方法
    age: getAge()
};

两种调用方法

getAge.apply(Buyi,[]); //this,指向了BUYI这个对象
Buyi.age();
getAge(); //会报错

5.内部对象

标准对象

typeof {}
"object"
typeof []
"object"
typeof Date
"function"
typeof Math.abs
"function"
typeof '123'
"string"
typeof 123
"number"
5.1 Date
var now = new Date();
now.getFullYear(); //年
now.getMonth(); //月 0-11
now.getDate(); //日
now.getDay();  //星期
now.getHours();
now.getMinutes();
now.getSeconds();
now.getTime(); //时间戳 1970年一月一日 00:00:00 至今的毫秒数


console.log(new Date(1)) //参数:时间戳
VM970:1 Thu Jan 01 1970 08:00:00 GMT+0800 (中国标准时间)
console.log(now)
VM881:1 Tue Jul 21 2020 17:46:43 GMT+0800 (中国标准时间)
console.log(now.getTime())
VM833:1 1595324803905

时区转换

yestody.toGMTString() //"Thu, 01 Jan 1970 00:00:00 GMT"
yestody.toDateString() //"Thu Jan 01 1970"
yestody //Thu Jan 01 1970 08:00:00 GMT+0800 (中国标准时间)
yestody.toLocaleString()//"1970/1/1 上午8:00:00"
yestody.toLocaleTimeString()//"上午8:00:00"
yestody.toLocaleDateString()//"1970/1/1"

5.2 JSON

json是什么

  • JSON(JavaScript Object Notation, JS 对象简谱) 是一种轻量级的数据交换格式。
  • 采用完全独立于编程语言的文本格式来存储和表示数据。
  • 简洁和清晰的层次结构使得 JSON 成为理想的数据交换语言。
  • 易于人阅读和编写,同时也易于机器解析和生成,并有效地提升网络传输效率。

在JavaScript中一切皆对象,任何js支持的类型都可以用JSON表示;

格式:

  • 对象用{}
  • 数组用[]
  • 所有的键值对都用 key:value
var user = {
    name:'BuYi',
    age:10
}
//对象 转 JSON字符串
let s = JSON.stringify(user);
//JSON字符串 转 对象
let parse = JSON.parse('{"name":"BuYi","age":10}');

JSON和对象区别:

{"name":"BuYi","age":10} //JSON
{name:'BuYi',age:10}     //对象

6.面向对象编程

6.1 什么时面向对象

类:模板

对象:具体的实例

面向对象的基本形式 java Python C#

但是在Javascript中有些不同

原型:
var user = {
    name:'BuYi',
    age:10,
    run:function () {
        console.log(this.name + 'run....');
    }
}
var xiaoming = {
    name: 'xiaoming'
}
xiaoming._proto_=user; //原型,和继承相似
var user = {
    name:'BuYi',
    age:10,
    run:function () {
        console.log(this.name + ' run....');
    }
}
var bird={
    fly:function () {
        console.log(this.name + ' fly...');
    }
}
var xiaoming = {
    name: 'xiaoming'
}
xiaoming.__proto__=bird;
class ES6

class继承

//新标准定义类
class Sutdent {
    //构造器
    constructor(name) {
        this.name = name;
    }

    //新增方法
    hello() {
        alert('hello');
    }
}
//老标准 定义类
var People = function () {
    this.name = name;
}
//想要新增方法
People.prototype.hello = function () {
    alert('hehe');
}

调用

var xiaoming = new Sutdent('xiaoming');

继承

class Sutdent {
    //构造器
    constructor(name) {
        this.name = name;
    }

    //方法
    hello() {
        alert('hello');
    }

}
class LittleStudent extends Sutdent{
    constructor(name,grade) {
        super().name = name;
        this.grade = grade;
    }
    myGrade(){
        alert('小学生');
    }
}
var xiaoming = new Sutdent('xiaoming');

原型链


7.操作BOM对象(重点)

JavaScript 和 浏览器关系?

JavaScript的诞生就是为了:让浏览器能够运行脚本

BOM:浏览器对象模型

window

window 代表 浏览器窗口

window.innerHeight;//窗口高
window.innerWidth; //窗口宽
window.outerHeight;//显示器高
window.outerWidth; // 显示器宽
Navigtor

封装了浏览器的相关信息

navigator.appName
"Netscape"
navigator.appVersion
"5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36"

大多数时候,不会使用这个对象,因为会被认为修改

不建议使用这些属性来判断和编写代码

screen
screen.width;
screen
Screen {availWidth: 1920, availHeight: 1040, width: 1920, height: 1080, colorDepth: 24,}
availHeight: 1040
availLeft: 0
availTop: 0
availWidth: 1920
colorDepth: 24
height: 1080
orientation: ScreenOrientation {angle: 0, type: "landscape-primary", onchange: null}
pixelDepth: 24
width: 1920
__proto__: Screen
location(重要)

代表当前页面的URL信息

host: "www.baidu.com"
hostname: "www.baidu.com"
href: "https://www.baidu.com/"
protocol: "https:"
reload: ƒ reload()  //刷新网页
//设置新的地址
location.assign('https://www.bilibili.com')
document

代表当前的页面,HTML DOM文档树

document.title
"哔哩哔哩 (゜-゜)つロ 干杯~-bilibili"
document.title='BenBuYi'
"BenBuYi"

获取具体的文档树节点

document.getElementById('bilibili')//获取相应ID对应的Html代码

获取cookie

document.cookie
"_uuid=5EA5A216-F9AA-A924-F50C-2705AD472A8343597infoc; buvid3=387021E3-2934-4FF2-A8D1-45C96DB122E670389infoc; CURRENT_FNVAL=16; rpdid=|(uYmYRmuYuJ0J'ulmlulRl~k; sid=6juia7ei; bsource=search_baidu; PVID=1"

劫持cookie原理

获取cookie到服务器,解析后获取账号密码

服务器端可是设置:cookle:httpOnly

history

代表浏览器的历史记录

history.back();
history.forward(); 

8.操作DOM对象(重点)

DOM:文档对象模型

核心:浏览器网页就是一个DOM属性结构

  • 更新:更新DOM节点
  • 遍历:遍历DOM节点,得到DOM节点
  • 删除:删除一个DOM节点
  • 添加:添加一个DOM节点
获得节点

要操作DOM节点,就要先获得这个DOM节点

<div id="father">
    <h1>标题一</h1>
    <p id="p1">p1</p>
    <p class="p2">p2</p>
</div>


<script>
    var h1 = document.getElementsByTagNameNS('h1') //标签选择器
    var p1 = document.getElementById('p1');
    var p2 = document.getElementsByClassName('p2');
    
    var fathers = document.getElementById('father');
    var childers = father.childern[index];//获取父节点下的所有子节点
    
    //fathers.firstChild;
    //fathers.lastChild;
</script>

原生代码,以后尽量使用jQuery

更新节点

操作HTML文本

<div id="father">
    <h1>标题一</h1>
    <p id="p1">p1</p>
    <p class="p2">p2</p>
</div>
<script>
    var id = document.getElementById('father');
</script>

id.innerText = '2e' 修改文本值

id.innerHTML = '<stong>12323g</strong>' 解析HTML文本标签

操作CSS(属性使用字符串,- 转为驼峰命名法)

id.style.fontSize = '200px'

id.style.color = 'red'

id.style.padding = '2em'

删除节点

删除节点的步骤,先获取父节点,在通过父节点的方法删除

id.removeChild(p1);

//如果不知道父节点是谁,可以用这种方法
var self = document.getElementById('p1');//先找自己
var id = self.parentElement;//再找父类
id.removeChild(p1);

//删除是一个动态的过程:
id.removeChild(id.children[0]); //删除h1后,p1就成了第0个
插入节点

获得了某个DOM节点后,假设这个DOM节点是空的,我们通过innerHTML就可以增加一个元素了,但如果不为空,增加元素会覆盖。

解决方法:

<p id="js">javaScript</p>
<div id ='list'>
    <p id="se">javaSE</p>
    <p id="ee">javaEE</p>
    <p id="me">javaME</p>
</div>

<script>
    var
        js = document.getElementById('js'),
        list = document.getElementById('list');
	list.appendChild(js); //追加

    //通过js创建新结点
    let newP = document.createElement('p');//创建p变迁
    newP.id = 'newP';
	newP.setAttribute('id','newP');//与上式等价,通用写法

    newP.innerText = '新的p';
	list.appendChild(newP);

	//setAttribute是通用写法 为标签添加属性
	var myScript = document.createElement('Script');
    myScript.setAttribute('type','text/javascript');

	//自己创建Style标签
    var myStyle = document.createElement('style');
    myStyle.setAttribute('type','text/css');
    myStyle.innerHTML = 'body{background-color: antiquewhite;}';
    document.getElementsByTagName('head')[0].appendChild(myStyle)</script>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-IdwpnRWe-1601040751200)(G:\Java_learn\笔记文件\前端笔记\pictures\image-20200722204910781.png)]

insert
<p id="js">javaScript</p>
<div id ='list'>
    <p id="se">javaSE</p>
    <p id="ee">javaEE</p>
    <p id="me">javaME</p>
</div>

<script>
    let ee = document.getElementById('ee');
    let js = document.getElementById('js');
    let list = document.getElementById('list');
    //此节点要包含目标节点 . insertBefore(新结点,目标节点) 将新结点插入到目标节点的前面
    list.insertBefore(js,ee);
</script>

9.操作表单(验证)

表单是什么 form
  • 文本框 input type = text
  • 下拉框 slect
  • 单选框 radio
  • 多选框 cheakbox
  • 隐藏域 hidden
  • 密码框 password

表单的目的:提交信息

获得要提交的信息
<span>用户名:</span><input type="text" id="username">

<script>
    let input_text = document.getElementById('username');
    //得到输入的数值 input_text.value
    
    //修改的得到的值
    input_text.value = '123';
</script>

input_text.value

document.getElementsByTagName(‘input’)[2].checked

<p>
    <span>用户名:</span><input type="text" id="username">
</p>
<p>
    <span>性别:</span><input type="radio" name="sex" value="boy"><input type="radio" name="sex" value="girl"></p>

<script>

    let input_text = document.getElementById('username');
    //得到输入的数值 input_text.value

    //修改的得到的值
    input_text.value = '123';

    //对于单选框、多选框等固定值,只能取到当前的值
    //document.getElementsByTagName('input')[1].value

    //document.getElementsByTagName('input')[2].checked
    //使用checked返回单选框是否被选中,false true 
</script>
提交表单(高级验证)
按钮绑定事件
<form action="#" method="post">
    <p>
        <span>用户名:</span><input type="text" id="username" name="username">
    </p>
    <p>
        <span>密码:</span><input type="password" id="password" name="password">
    </p>
    <!--绑定事件-->
    <button type="submit" onclick="aaa()">提交</button>
</form>

<script>
        function aaa() {
            let user = document.getElementById('username');
            let pwd = document.getElementById('password');
            pwd.value = MD5(pwd.value);
            console.log(user.value);
            console.log(pwd.value);
        }
</script>

MD5加密代码

'use strict';
function MD5(instring){
    var hexcase = 0;   /* hex output format. 0 - lowercase; 1 - uppercase        */
    var b64pad  = "";  /* base-64 pad character. "=" for strict RFC compliance   */

    /*
     * These are the functions you'll usually want to call
     * They take string arguments and return either hex or base-64 encoded strings
     */
    function hex_md5(s)    { return rstr2hex(rstr_md5(str2rstr_utf8(s))); }
    function b64_md5(s)    { return rstr2b64(rstr_md5(str2rstr_utf8(s))); }
    function any_md5(s, e) { return rstr2any(rstr_md5(str2rstr_utf8(s)), e); }
    function hex_hmac_md5(k, d)
    { return rstr2hex(rstr_hmac_md5(str2rstr_utf8(k), str2rstr_utf8(d))); }
    function b64_hmac_md5(k, d)
    { return rstr2b64(rstr_hmac_md5(str2rstr_utf8(k), str2rstr_utf8(d))); }
    function any_hmac_md5(k, d, e)
    { return rstr2any(rstr_hmac_md5(str2rstr_utf8(k), str2rstr_utf8(d)), e); }

    /*
     * Perform a simple self-test to see if the VM is working
     */
    function md5_vm_test()
    {
        return hex_md5("abc").toLowerCase() == "900150983cd24fb0d6963f7d28e17f72";
    }

    /*
     * Calculate the MD5 of a raw string
     */
    function rstr_md5(s)
    {
        return binl2rstr(binl_md5(rstr2binl(s), s.length * 8));
    }

    /*
     * Calculate the HMAC-MD5, of a key and some data (raw strings)
     */
    function rstr_hmac_md5(key, data)
    {
        var bkey = rstr2binl(key);
        if(bkey.length > 16) bkey = binl_md5(bkey, key.length * 8);

        var ipad = Array(16), opad = Array(16);
        for(var i = 0; i < 16; i++)
        {
            ipad[i] = bkey[i] ^ 0x36363636;
            opad[i] = bkey[i] ^ 0x5C5C5C5C;
        }

        var hash = binl_md5(ipad.concat(rstr2binl(data)), 512 + data.length * 8);
        return binl2rstr(binl_md5(opad.concat(hash), 512 + 128));
    }

    /*
     * Convert a raw string to a hex string
     */
    function rstr2hex(input)
    {
        try { hexcase } catch(e) { hexcase=0; }
        var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
        var output = "";
        var x;
        for(var i = 0; i < input.length; i++)
        {
            x = input.charCodeAt(i);
            output += hex_tab.charAt((x >>> 4) & 0x0F)
                +  hex_tab.charAt( x        & 0x0F);
        }
        return output;
    }

    /*
     * Convert a raw string to a base-64 string
     */
    function rstr2b64(input)
    {
        try { b64pad } catch(e) { b64pad=''; }
        var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
        var output = "";
        var len = input.length;
        for(var i = 0; i < len; i += 3)
        {
            var triplet = (input.charCodeAt(i) << 16)
                | (i + 1 < len ? input.charCodeAt(i+1) << 8 : 0)
                | (i + 2 < len ? input.charCodeAt(i+2)      : 0);
            for(var j = 0; j < 4; j++)
            {
                if(i * 8 + j * 6 > input.length * 8) output += b64pad;
                else output += tab.charAt((triplet >>> 6*(3-j)) & 0x3F);
            }
        }
        return output;
    }

    /*
     * Convert a raw string to an arbitrary string encoding
     */
    function rstr2any(input, encoding)
    {
        var divisor = encoding.length;
        var i, j, q, x, quotient;

        /* Convert to an array of 16-bit big-endian values, forming the dividend */
        var dividend = Array(Math.ceil(input.length / 2));
        for(i = 0; i < dividend.length; i++)
        {
            dividend[i] = (input.charCodeAt(i * 2) << 8) | input.charCodeAt(i * 2 + 1);
        }

        /*
         * Repeatedly perform a long division. The binary array forms the dividend,
         * the length of the encoding is the divisor. Once computed, the quotient
         * forms the dividend for the next step. All remainders are stored for later
         * use.
         */
        var full_length = Math.ceil(input.length * 8 /
            (Math.log(encoding.length) / Math.log(2)));
        var remainders = Array(full_length);
        for(j = 0; j < full_length; j++)
        {
            quotient = Array();
            x = 0;
            for(i = 0; i < dividend.length; i++)
            {
                x = (x << 16) + dividend[i];
                q = Math.floor(x / divisor);
                x -= q * divisor;
                if(quotient.length > 0 || q > 0)
                    quotient[quotient.length] = q;
            }
            remainders[j] = x;
            dividend = quotient;
        }

        /* Convert the remainders to the output string */
        var output = "";
        for(i = remainders.length - 1; i >= 0; i--)
            output += encoding.charAt(remainders[i]);

        return output;
    }

    /*
     * Encode a string as utf-8.
     * For efficiency, this assumes the input is valid utf-16.
     */
    function str2rstr_utf8(input)
    {
        var output = "";
        var i = -1;
        var x, y;

        while(++i < input.length)
        {
            /* Decode utf-16 surrogate pairs */
            x = input.charCodeAt(i);
            y = i + 1 < input.length ? input.charCodeAt(i + 1) : 0;
            if(0xD800 <= x && x <= 0xDBFF && 0xDC00 <= y && y <= 0xDFFF)
            {
                x = 0x10000 + ((x & 0x03FF) << 10) + (y & 0x03FF);
                i++;
            }

            /* Encode output as utf-8 */
            if(x <= 0x7F)
                output += String.fromCharCode(x);
            else if(x <= 0x7FF)
                output += String.fromCharCode(0xC0 | ((x >>> 6 ) & 0x1F),
                    0x80 | ( x         & 0x3F));
            else if(x <= 0xFFFF)
                output += String.fromCharCode(0xE0 | ((x >>> 12) & 0x0F),
                    0x80 | ((x >>> 6 ) & 0x3F),
                    0x80 | ( x         & 0x3F));
            else if(x <= 0x1FFFFF)
                output += String.fromCharCode(0xF0 | ((x >>> 18) & 0x07),
                    0x80 | ((x >>> 12) & 0x3F),
                    0x80 | ((x >>> 6 ) & 0x3F),
                    0x80 | ( x         & 0x3F));
        }
        return output;
    }

    /*
     * Encode a string as utf-16
     */
    function str2rstr_utf16le(input)
    {
        var output = "";
        for(var i = 0; i < input.length; i++)
            output += String.fromCharCode( input.charCodeAt(i)        & 0xFF,
                (input.charCodeAt(i) >>> 8) & 0xFF);
        return output;
    }

    function str2rstr_utf16be(input)
    {
        var output = "";
        for(var i = 0; i < input.length; i++)
            output += String.fromCharCode((input.charCodeAt(i) >>> 8) & 0xFF,
                input.charCodeAt(i)        & 0xFF);
        return output;
    }

    /*
     * Convert a raw string to an array of little-endian words
     * Characters >255 have their high-byte silently ignored.
     */
    function rstr2binl(input)
    {
        var output = Array(input.length >> 2);
        for(var i = 0; i < output.length; i++)
            output[i] = 0;
        for(var i = 0; i < input.length * 8; i += 8)
            output[i>>5] |= (input.charCodeAt(i / 8) & 0xFF) << (i%32);
        return output;
    }

    /*
     * Convert an array of little-endian words to a string
     */
    function binl2rstr(input)
    {
        var output = "";
        for(var i = 0; i < input.length * 32; i += 8)
            output += String.fromCharCode((input[i>>5] >>> (i % 32)) & 0xFF);
        return output;
    }

    /*
     * Calculate the MD5 of an array of little-endian words, and a bit length.
     */
    function binl_md5(x, len)
    {
        /* append padding */
        x[len >> 5] |= 0x80 << ((len) % 32);
        x[(((len + 64) >>> 9) << 4) + 14] = len;

        var a =  1732584193;
        var b = -271733879;
        var c = -1732584194;
        var d =  271733878;

        for(var i = 0; i < x.length; i += 16)
        {
            var olda = a;
            var oldb = b;
            var oldc = c;
            var oldd = d;

            a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
            d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
            c = md5_ff(c, d, a, b, x[i+ 2], 17,  606105819);
            b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
            a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
            d = md5_ff(d, a, b, c, x[i+ 5], 12,  1200080426);
            c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
            b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
            a = md5_ff(a, b, c, d, x[i+ 8], 7 ,  1770035416);
            d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
            c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
            b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
            a = md5_ff(a, b, c, d, x[i+12], 7 ,  1804603682);
            d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
            c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
            b = md5_ff(b, c, d, a, x[i+15], 22,  1236535329);

            a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
            d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
            c = md5_gg(c, d, a, b, x[i+11], 14,  643717713);
            b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
            a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
            d = md5_gg(d, a, b, c, x[i+10], 9 ,  38016083);
            c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
            b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
            a = md5_gg(a, b, c, d, x[i+ 9], 5 ,  568446438);
            d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
            c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
            b = md5_gg(b, c, d, a, x[i+ 8], 20,  1163531501);
            a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
            d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
            c = md5_gg(c, d, a, b, x[i+ 7], 14,  1735328473);
            b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);

            a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
            d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
            c = md5_hh(c, d, a, b, x[i+11], 16,  1839030562);
            b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
            a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
            d = md5_hh(d, a, b, c, x[i+ 4], 11,  1272893353);
            c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
            b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
            a = md5_hh(a, b, c, d, x[i+13], 4 ,  681279174);
            d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
            c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
            b = md5_hh(b, c, d, a, x[i+ 6], 23,  76029189);
            a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
            d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
            c = md5_hh(c, d, a, b, x[i+15], 16,  530742520);
            b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);

            a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
            d = md5_ii(d, a, b, c, x[i+ 7], 10,  1126891415);
            c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
            b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
            a = md5_ii(a, b, c, d, x[i+12], 6 ,  1700485571);
            d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
            c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
            b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
            a = md5_ii(a, b, c, d, x[i+ 8], 6 ,  1873313359);
            d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
            c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
            b = md5_ii(b, c, d, a, x[i+13], 21,  1309151649);
            a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
            d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
            c = md5_ii(c, d, a, b, x[i+ 2], 15,  718787259);
            b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);

            a = safe_add(a, olda);
            b = safe_add(b, oldb);
            c = safe_add(c, oldc);
            d = safe_add(d, oldd);
        }
        return Array(a, b, c, d);
    }

    /*
     * These functions implement the four basic operations the algorithm uses.
     */
    function md5_cmn(q, a, b, x, s, t)
    {
        return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
    }
    function md5_ff(a, b, c, d, x, s, t)
    {
        return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
    }
    function md5_gg(a, b, c, d, x, s, t)
    {
        return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
    }
    function md5_hh(a, b, c, d, x, s, t)
    {
        return md5_cmn(b ^ c ^ d, a, b, x, s, t);
    }
    function md5_ii(a, b, c, d, x, s, t)
    {
        return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
    }

    /*
     * Add integers, wrapping at 2^32. This uses 16-bit operations internally
     * to work around bugs in some JS interpreters.
     */
    function safe_add(x, y)
    {
        var lsw = (x & 0xFFFF) + (y & 0xFFFF);
        var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
        return (msw << 16) | (lsw & 0xFFFF);
    }

    /*
     * Bitwise rotate a 32-bit number to the left.
     */
    function bit_rol(num, cnt)
    {
        return (num << cnt) | (num >>> (32 - cnt));
    }

    return hex_md5(instring);
}
表单绑定标签
<!--
表单绑定提交事件
onsubmit = 绑定一个提交测试的函数,获取一个true或false
将这个结果返回给表单,使用onsubmit接收
-->
<form action="https://www.baidu.com" method="post" onsubmit="return aaa()">
    <p>
        <span>用户名:</span><input type="text" id="username" name="username">
    </p>
    <p>
        <span>密码:</span><input type="password" id="input_password" >
    </p>
    <input type="hidden" id="md5-pwd" name="password">
    <!--绑定事件-->
    <button type="submit" >提交</button>
</form>

<script>
        function aaa() {
            let user = document.getElementById('username');
            let pwd = document.getElementById('input_password');
            let Md5_pwd = document.getElementById('md5-pwd');
            Md5_pwd.value = MD5(pwd.value);

            //可以再次判断表单内容,true就是通过,false阻止提交
            return true;
        }
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值