JavaScript笔记(前两章是英文)

1. JavaScript

1.1. Quick learn

Introduce Js into html files.

There are two ways to introduce Js file into html:

  1. Inside label.

    just use a label to introduce.

  2. Outside label.

    use label “script” to link html and Js.

<!DOCTYPE html>
<html lang = "en">
<head>
  <meta charset = "UTF-8">
  <title>1.first js file</title>
  
  <!--
      js code should be written in label "script", just like css.
      you can also save it in the label "body".
  -->
  <script>
      alert("helloWorld");
  </script>
  
  <!--
    Use this way to introduce js file.
    Be careful:
      this is not a closed label.
    default type of script label is "text/javascript", so there is no need to add this attribute.
  -->
  <script src="js/qj.js"></script>
  
</head>
<body>

</body>
</html>
alert("helloWorld");

1.2 Basic grammar

  1. Define a variable.

    the only type of variable is “var”, and the actually type is decided to your content after that.

  2. Condition control.

    Careful:

    You must tell the higher case or lower case of letters.

    if(condition){...}
    
    if(condition) {
    	if(condition) {
    		...
    	}
    	...
    }
    
  3. Type of data.

    number; text; graph; video; radio…

//1. define a variable.
var name = "hello?";
alert(name);

//condition control
var score = 1;
if (2 > 1) {
    if (score > 60 && score < 100) {
        alert("congratulations.");
    } else {
        alert("go on.");
    }
    alert("2 > 1");
}

/*
* console.log(score)
* print the var in browser.
* */


//====================================
//Type of data

/*
* 123 Integer
* 123.456 Decimal
* 1.23e4 Scientific notation
* -99 Negative number
* Nan not a number
* Infinity a num of infinity
*
* Notion: nan is not equal to another nan, in fact it's not equal to any number.
*   The only way to judge if a number is nan is to use method "isNaN(var)"
* */

var isNan = isNaN(score);

/*
* 'abc' and "abc"
* sometimes you may use Escape characters, that's all the same with Java.
* */

/*
* boolean is the same with Java
* */

/*
* logic characters
* "&&" and "||" and "!"
* */

/*
* compare character
* = assignment
* == equal
* === absolute equal
*
* Only if the two data is equal in both datum and type, the "===" would be "true", so we use "===" in most situations.
* */

/*
* null and undefine.
* */

/*
* Array
* A series of data. The type of them might be different.
* */
//in order to make sure the codes is readable enough,use this type of Array defining.
var arr = [1,2,3,"hello",true,'word'];
//instead of this.
new Array(1,2,3,"hello",true,'word');

//traverse the array
//if the subscript is out of the boundary, it will show "undefine" message.
for (var i = 0;i < 6;i++) {
    alert(arr[i]);
}

/*
* Define an Object.
*
* use "," between every two attributes
* no "," or ";" at the last one.
* */
var Person = {
    name: "zhangSan",
    age: "3",
    tages: "xxoo"
};

1.3 Strict inspection mod

In ES6, when crating a local var, please use “let” instead of “var”.

If you want to avoid the problems of the casual use in JavaScript, add

'use strict’

at the head of Js code to open the strict inspection mod.

2. Data type

2.1. String

  1. A normal string could be assigned with two apostrophes or double quotes.
  2. Be careful the escape characters: \
  3. Multi-line string
  4. Template string
  5. Length of a string
  6. Print a letter of the existed string.(It wouldn’t change the original string.)
  7. Make all letters to upper/lower case.(it’s a method instead of attribute)
  8. check the index of a special letter.
  9. cut the string
'use strict'

console.log('a');
console.log("a");

console.log('a\'');

//use ' ` ' to make a multi-line string.
var msg = `
hello
world.
`

let name = "zht1702";
let age = 12;

//you can use ${} to show a var that is also existed.
let message = `hello! ${name}`

let stu = "student";
//to print out the length of a string.
console.log(stu.length);

console.log(stu.toUpperCase());

console.log(stu.indexOf(u));

console.log(stu.substring(3));

console.log(stu.substring(2,4));

2.2. Array

Array in Js could contain any type of data.

'use strict'

//crate an array.
let arr = [3,5,1,4,7,2,3];

//print it.
console.log(arr);

//1. length.
console.log(arr.length);

/*
* You can change the length of arrays in Js.
*   if you change the length from 6 to 10, then the 4 new elements would be "empty" elements.
* */
arr.length = 10;

/*
* If you turn it to a shorter length, the elements overflowed would be lost.
* */
arr.length = 5;

//use subscript would visit the value of element in arr.


//2. indexOf(); get the corresponding element at the subscript.
console.log(arr.indexOf(3));

//3. slice(); -->  cut a part of array, and return a new array, similar to "substring()" in string.
let arr2 = arr.slice(2,4);
console.log(arr2)

//4. push/pop(); --> add new element / delete elements.
//  use "push()" to add a new element after elements existed elements, and use "pop()" to delete the last element.
arr.push("a");
arr.push('b');
arr.pop();
arr.pop();

//5. unshift/shift --> add/delete element at the head.
//  similar to push/pop, but the aim is the head of arr.

//6. sort --> put elements in order.
arr.sort();

//7. reverse --> get arr reversed.
arr.reverse();

//8. concat();
//  Be Careful: it would return a new arr!
arr = arr.concat(['a','b','c']);

//9. link character.
//  --> print the concatenation array, use special character to link elements.
//  --> it returns a new string.
let newArr = arr.join('-');

//10. multi-arr
let newArr2 = [[1,2],[3,4],[5,6]];

/*the method to visit the element in multi-arr is the same to javaSE.*/

//11. fill() --> use to fill the arr with a letter/string(means this element will cover all elements of the aim arr.)

//12. find();

2.3. object

Object in Js is built up with many key-value pairs, use a {…} to represent an object and “key : value” as attributes of the object, use ‘,’ between every two attributes(except the last).

var <nameOfObject> = {
	attributeKey: value,
	attributeKey: value,
	...
}

use an attribute that is not existed wouldn’t report an error, but report an “undefined”

//crate an object "person" and its four attributes.
var person = {
    name: "zht1702",
    age: 14,
    email: "1234@567",
    score: 123
}

/*
* In Js, all keys are string, values could be any type.
* */

//1. Assignment
person.name = "zhangSan";

//2. Use an attribute that is not existed wouldn't report an error, but report an "undefined"

//3. Dynamically delete attributes.
//  delete --> return a boolean to show if delete successfully, if you delete an attribute, when you visit it again, it will be "undefined".
delete person.email;

//4. Dynamically add attributes.
//  the object would have a new attribute.
person.haha = "haha";

//5. Judge if the attribute in the object.
'age' in person;

//6. Judge if an attribute is the object own.
//  hasOwnProperty
person.hasOwnProperty("name");

2.4. 流程控制

'use strict'

//if判断语句
let age = 3;

if (age > 3) {
    alert("agr > 3");
} else {
    alert("age <= 3");
}

//循环
while (age < 10) {
    age++;
}
//for循环
for (let i = 0;i < 4;i++) {
    age--;
}

let arr = [1,3,45,6,2,3,5,7,9];

//forEach循环
arr.forEach(function (value) {console.log(value)});

//for in 循环 --> 类似于java的foreach循环
for (let num in age) {
    console.log(num);
}

//for of 循环,建议使用for of而不是for in
for (let x of arr) {
    console.log(x);
}

2.5. map和set

'use strict'

//es6新特性
new Map();
new Set();

//Map键值对
//统计学生的成绩和名字
let map = new Map([["tom",100],["jack",90],["haha",70]]);
//通过key获取value
let name = map.get("tom");
console.log(name);
//赋值
map.set("admin",999);
//删除键值对
map.delete("tom");

//Set
//Java中的set是无需不重复集合
//set集合可以去重
let set = new Set([1,2,3,4,5,1,2,1,5]);
//添加元素
set.add(8);
//删除元素
set.delete(5);
//判断是否存在值的两种方法
console.log(3 in set);
let ifHasTri = set.has(3);

3. 函数以及面向对象

3.1. 定义函数以及参数的获取

'use strict'

//函数定义1:
//用function定义函数,没有返回值类型,其余的和java的函数定义相同
function abs(x) {
    //手动规范传入参数
    if (typeof x != 'number') {
        //手动抛出异常
        throw 'Nota a number.'
    }
    if (x >= 0) {
        return x;
    } else {
        return -x;
    }
}
//一旦执行到return代表函数结束,返回结果
//如果没有执行return,函数执行完也会返回结果(undefined)
let num = -45;
console.log(abs(num));

//定义方式2
//相当于是把后面的函数传给前面的标识符,从而达到标识符代表后面函数的功能
//两种定义方式有相同的效果,只是写法不同
//这是一个匿名函数,func,通过func调用函数
let func = function (x) {
    if (x >= 0) {
        return x;
    } else {
        return -x;
    }
}

//函数调用
//函数调用的基本用法同java

/*
* 1. 参数问题:
* Js可以传递任意函数,也可以不传递,返回undefined
*
* 2. 参数存在问题:
* 手动规范参数类型,采用抛出异常等方式
*
* 3. arguments是一个关键字,用来表示传入函数的参数
* 例如,函数中写 arguments.length 可以获得传入该函数的参数的数量
*   通过遍历arguments可以做到遍历所有参数的功能
*
*
*4. 问题:arguments包含了所有的参数,我们有时候想要使用多余的参数来进行附加操作,需要排除已有的参数(且这个已有参数是不固定的)
*
* */
function abs2(x) {
    //遍历函数传入参数并打印
    for (let i = 0;i < arguments.length;i++) {
        console.log(arguments[i]);
    }
    //手动规范传入参数
    if (typeof x != 'number') {
        //手动抛出异常
        throw 'Nota a number.'
    }
    if (x >= 0) {
        return x;
    } else {
        return -x;
    }
}

/*
* ES6新特性,
* rest --> 获取除了已经定义的参数以外的所有参数
* */
//使用rest必须在函数参数列表标记"...rest",这样可以用rest将多余的参数保存起来,注意,rest参数必须写在最后面
function func2(a,b,...rest) {
    //打印前两个参数
    console.log("a = " + a + ",b = " + b);

    console.log(rest);
}

3.2. 变量的作用域

全局作用域

  1. 在Js中,var定义的变量实际是有作用域的

    如果在函数体中声明,则在函数体外不可使用(非要实现的话,可以研究闭包)

  2. 如果两个函数使用了相同的变量名,只要分别在函数内部,就不会冲突

  3. 在嵌套的情况下(不论是循环,判断还是函数嵌套),里层的可以访问外部的成员,但是外部不能访问内部成员

  4. 嵌套中出现内外函数重名的情况下,从当前函数自生开始向外查找,假设外部存在这个重名的函数变量,则内部函数会屏蔽外部函数变量

  5. 先使用后定义一个变量的话,使用时,这个变量会变成undefined

    可以理解成,Js执行引擎自动提升了变量的申明,但是不会提升赋值

    所以一般会把所有变量的定义统一到最前面,便于代码的维护

  6. 全局函数

  7. 全局对象window

    默认所有的全局变量,都会绑定在window对象下

var x = 'xxx';
alert(x);
alert(windos.x);
//效果是一样的
//alert本身也是一个window对象
window.alert(x);

参照之前总结的,任何函数都可以用变量调用,所以就有了一种神奇的操作:

var new_alert = window.alert;
new_alert('hello');

Js实际上只有一个全局作用域,任何变量(包括函数也可以视作变量),假设没有在函数作用范围内找到,就会向外查找,如果在全局作用域都没有找到,就会报错

规范:

由于所有的全局变量都会绑定到window上,如果不同的Js文件使用了相同的全局变量,怎么解决?

也即,如何减少冲突?

解决:定义一个唯一全局变量,而不是将所有变量绑定在window上

//唯一全局变量
var vars = {};

//定义全局变量
vars.name = 'hello';
vars.abs = function(a) {return -a;}

把自己的代码全部放入自己定义的唯一空间名字中,降低全局命名冲突的问题

局部作用域let:

function aaa() {
	for(var i = 0;i < 100;i++) {
		console.log(i);
	}
	console.log(i++);//事实证明这一行的i任然有效,并可以使用
}

为了解决上述作用域问题,ES6引入了let变量来解决局部作用域冲突问题,建议使用let定义局部作用域变量

function aaa() {
	for(let i = 0;i < 100;i++) {
		console.log(i);
	}
	console.log(i++);//事实证明这一行的i任然有效,并可以使用
}

常量const:

在ES6之前定义常量,一般只是用全大写字母表示变量表示这个变量是常量(建议不要修改这样的变量)

在ES6引入了常量const关键字

3.3. 方法

方法就是把函数放在对象内部即可,对象只有两个东西,属性和方法

let Person = {
    name:'person',
    birth:2001,
    //方法
    age: function () {
        //今年 - 出生年份
        let now = new Date().getFullYear();
        return now - this.birth;
    }
}

调用属性和方法:

//属性
Person.name
//方法,一定要带有括号
Person.age()

第一段代码中的this代表什么?

如果把第一段代码拆开则有:

let Person = {
    name:'person',
    birth:2001,
    //方法
    age: getAge
}

function getAge(){
    //今年 - 出生年份
    let now = new Date().getFullYear();
    return now - this.birth;
}

上述代码执行成功

输入Person.age() 返回正确的值

输入getAge() 返回NaN

单独调用getAge会默认是window调用的,所以会出错

**注意:**this只能默认指向调用它的对象,除了apply函数

apply函数

在Js中可以控制this的指向

function getAge(){
    //今年 - 出生年份
    let now = new Date().getFullYear();
    return now - this.birth;
}

let person = {
    name:'person',
    birth:2001,
    //方法
    age: getAge
};

//this指向了Person对象,参数为空
//括号的第一个参数是指向的对象,第二个是参数列表,没有参数所以不写
//注意getAge后面别加括号...
getAge.apply(person,[]);

4. 内部对象

标准对象

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-wevjSRRx-1629537518942)(pic/Js/image-20210816191440618.png)]

4.1. Date

Date是一个日期类型

基本使用

let now = new Date();
//Mon Aug 16 2021 19:16:31 GMT+0800 (中国标准时间)

now.getFullYear();  //获取年份
now.getMonth();     //获取月份  //0 - 11 代表月
now.getDate();      //获取日
now.getDay();       //获取周几
now.getHours();     //获取时
now.getMinutes();   //获取分
now.getSeconds();   //获取秒

now.getTime();      //获取时间戳 时间戳时全世界统一的,从1970.1.1.0.00.000

console.log(new Date(1629112931416));//时间戳转具体时间
//Mon Aug 16 2021 19:22:11 GMT+0800 (中国标准时间)

//获取本地时间
now.toLocaleString();//"2021/8/16 下午7:23:38"
now.toLocaleTimeString();//"下午7:23:22"

转换

//获取本地时间
//这些是方法,不是属性
now.toLocaleString();//"2021/8/16 下午7:23:38"
now.toLocaleTimeString();//"下午7:23:22"

//转换
now.toGMTString();
//"Mon, 16 Aug 2021 11:27:17 GMT"

4.2. JSON

Json是什么?

Json是一种轻量级的数据交换格式

清晰简洁的层次结构使得JSON成为理想的数据交换语言

易于人的阅读和编写,同时也易于机器解析和生成,并有效地提高网络传输速率

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

格式:

  • 对象都用大括号(花括号)
  • 数组都用中括号
  • 所有的键值对都用 key : value 格式

JSON字符串和Js对象的转换:

    let user = {
        name:"zhangSan",
        age:"3",
        sex:'nan'
    };

    //对象转换成JSON字符串
    let str = JSON.stringify(user);
    //"{\"name\":\"zhangSan\",\"age\":\"3\",\"sex\":\"nan\"}"

    //JSON转换成对象
    let originalUser = JSON.parse(str);
    //注意:直接放进去JSON字符串的话,外面加单引号
    let originalUser2 = JSON.parse('{\"name\":\"zhangSan\",\"age\":\"3\",\"sex\":\"nan\"}');

4.3. AJAX

  • 原生的Js写法 xhr 异步请求
  • jQuery 封装好的方法 $("#name").ajax("")
  • axios 请求

5. 面向对象编程

5.1. 什么是面向对象

JavaScript, Java, C# … 均为面向对象,但是Js有一些区别:

Java中的:

  • 类: 模板

  • 对象: 具体的实例

在Js中,以上概念需要改变一下思维方式

//原来的对象 -> 原型对象(其实就是父类)
let student = {
    name:"zhangSan",
    age:"3",
    sex:'nan',
    run: function () {
        console.log(this.name + " is Running.");
    }
};

//ming
let ming = {
    name:"xiaoMing",

}

//设置ming的原型为user,从而ming可以继承到user的内容
ming._proto_ = user;

class继承

class关键字是在ES6引入的

//ES6以后,给student新增一个方法
//定义一个学生类
class student{
    //构造器只需要写一个constructor就可以了
    constructor(name){this.name = name;}

    //创建一个方法
    hello () {alert("hello!");}
}

创建新对象

//利用 模板/原型/类 创建新对象
let ming = new student("ming");

子类继承父类:

//子类继承父类
class primaryStudent extends student{

    constructor (name,grade) {
        //调用父类构造方法
        super(name);
        this.grade = grade;
    }

    myGrade () {alert("I'm a primory student.")}

}

注意,本质仍然是Js的原型,只是写法更人性化了

原型链

6. 操作BOM对象

浏览器介绍

Js 和 浏览器 的关系

Js的诞生就是为了能够在浏览器中运行

BOM:浏览器对象模型

  • IE 6-11
  • chrome
  • safari
  • fireFox
  • Opera

以及各种第三方浏览器…

window对象

window对象代表浏览器窗口

navigator (不建议使用)

Navigator 封装了浏览器的信息

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-mSwDeBxH-1629537518944)(C:\Users\ZhangHaotian\AppData\Roaming\Typora\typora-user-images\image-20210817112819831.png)]

大多数时候,不会使用navigator对象,因为会被人人为修改

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

screen

代表屏幕尺寸

screen.height
1080
screen.width
1920

单位一般是px(像素)

loction

loction 代表当前页面的URL信息

location也是一个对象

其中,host表示主机,href表示当前指向的位置,protocol表示协议,reload表示重新加载(是一个方法)

host: "www.baidu.com" 
href: "https://www.baidu.com/"
protocol: "https:"
reload: ƒ reload()	//重新加载网页/刷新

//设置新的地址
location.assign("https://www.bing.com/?mkt=zh-CN");

document

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

//检查当前网页标题
document.title
"必应"

//修改标题
document.title = "hello"
"hello"

获取具体的文档树节点:

<dl id="dl">
    <dt>JAVA</dt>
<dd>JavaSE</dd>
<dd>JavaEE</dd>
</dl>

<script>
    let dl = document.getElementById("dl");
</script>

document可以获取网页的cookie

document.coockie

于是有人可以利用js代码获取coockie上传到他自己的服务器,从而达到劫持coockie的目的

history

history 代表浏览器的历史记录

history;

//前进
history.back();

//后退
history.forward();

7. 操作DOM对象(重点)

DOM 文件对象模型

核心

浏览器网页就是一个DOM树形结构

  • 更新: 更新DOM节点
  • 遍历dom节点: 得到DOM节点
  • 删除: 删除目标dom节点
  • 添加: 添加一个新的节点

要操作一个dom节点,就要先得到该节点

获得DOM节点:

//对应的是css的选择器
let h1 = document.getElementsByTagName("h1");
let p1 = document.getElementById("p1");
let p2 = document.getElementsByClassName("p2");

let father = document.getElementById("father");

//获得父节点下的所有子节点
let childs = father.children;

//获取第一个和最后一个子节点
father.firstChild;
father.lastChild;

以上是原生代码,之后会尽量使用jQuery

//获取节点
let id1 = document.getElementById("test");

更新节点

  • 修改文本的值: test.innerText = '123';
  • 可以解析HTML文本标签:test.innerHTML="<strong>123</strong>"

修改css

//修改颜色  属性使用字符串包围
test.style.color = 'red';
//注意,这种连接的属性,由于Js中间不能用-,所以用驼峰命名
test.style.fontSize = '24px';
id1.style.margin = '32px';

删除节点

删除节点的步骤: 先获取父节点,然后通过父节点删除自己

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

<script>
    'use strict'

//利用父节点删除子节点p1
father.removeChild(p1);        
</script>

或者全部用代码实现:

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

    <script>
        'use strict'

        //获取子节点
        let self = document.getElementById("p1");
        //利用子节点获取父节点
        let father = p1.parentElement;
        //利用父节点删除子节点
        father.removeChild(p1);
        
    </script>

或者利用children数组进行删除:

father.removeChild(father.children[0]);
father.removeChild(father.children[0]);
father.removeChild(father.children[0]);

注意:删除节点的时候要 注意,删除掉一个节点后,后面的节点会跟进到这个节点上

插入节点

我们获得了某个dom节点,假设这个dom节点是空的,则通过innerHTML就可以增加一个元素了,但是如果这个dom节点已经存在元素了,我们就不能这么做,否则原来的节点会被覆盖

所以一般采用追加操作

<!DOCTYPE html>

<html>
    <head>
        <meta charset="UTF-8">
        <title>index</title>
    </head>

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

    </body>
</html>

js代码:

'use strict'

let 
js = document.getElementById('js'),
    list = document.getElementById('list');

//把js追加到list最后面,相当于是吧js移动到list的末尾
list.append(js);

//如何创建并且放入一个新的节点?
let newP = document.createElement('p');//创建一个新的p标签
//设置一个id
newP.id = 'newP';
//设置文本内容
newP.innerText = 'helloWorld.';
//添加标签到list结尾
list.append(newP);

通过attribute添加和设置属性值:

//创建一个标签节点
let myScript = document.createElement('script');
//设置标签属性值,第一个参数是属性名字,第二个参数是属性值
myScript.setAttribute('type','text/javaScript');
//追加
list.append(myScript);

插入样式标签:

//创建style标签
let myStyle = document.createElement('style');
//标记css文本
myStyle.setAttribute('type','text/css');
//设置css样式
myStyle.innerHTML = 'body{background-color: orange}';
//在head标签的末尾添加这个style标签
//注意,因为获取的head是一个collection,而head标签是这个collection的第0个元素,所以要用方括号取下标
document.getElementsByTagName('head')[0].appendChild(myStyle);

插入前面:

//获取ee节点和js节点
let ee = document.getElementById('ee');
let js = document.getElementById('js');
let list = document.getElementById('list');
//在ee前面插入js节点
//要包含的节点.insertbefore(新节点,目标节点)
list.insertBefore(js,ee);

8. 操作表单(验证)

表单是什么?

form, DOM树

  • 文本框 text
  • 下拉框 select标签
  • 复选框 radio
  • 单选框 checkbox
  • 隐藏域 hidden
  • 密码框 password

表单的目的: 提交信息

获得要提交的信息

//得到输入框的值
let userName = document.getElementById('username');
//修改输入框的值
userName.value = 'hello';

//获取复选框的对象
let boy_radio = document.getElementById('boy');
let girl_radio = document.getElementById('girl');

//对于单选框,多选框等,用value只能获取选项本身的值
//判断是否被选中
boy_radio.checked; //查看返回结果是否为true,如果是,则说明已经被选中

提交表单

利用md5算法加密提交信息

<!DOCTYPE html>

<html>
<head>
    <meta charset="UTF-8">
    <title>demo</title>

    <!--MD5工具类-->
    <script src="https://cdn.bootcss.com/blueimp-md5/2.10.0/js/md5.min.js"></script>

</head>

<body>
    <form method="POST" action="#">

        <p>
            <span>username:</span> <input type="text" id="username" required name="username">
        </p>

        <p>
            <span>pwd</span> <input type="password" id="password" required name="password">
        </p>

        <!--绑定事件 onclick 被点击-->
        <button type="submit" onclick="checkButton()">commit</button>
    </form>
    <script>
        //获取表单内容并进行检查
        function checkButton() {
            let uname = document.getElementById('username');
            let pwd = document.getElementById('password');
            console.log(uname.value);
            //可以在中途改变表单提交值
            //加密算法: MD5算法
            pwd.value = md5(pwd.value);

            //pwd.value = 'apple';
            console.log(pwd.value);
        }
    </script>
</body>
</html>

最优解: 表单级别的加密和函数验证

<!DOCTYPE html>

<html>
<head>
    <meta charset="UTF-8">
    <title>demo</title>

    <!--MD5工具类-->
    <script src="https://cdn.bootcss.com/blueimp-md5/2.10.0/js/md5.min.js"></script>

</head>

<body>
    <!--表单绑定提交事件
        onsubmit = 绑定一个提交检测的函数  true/false 
        将结果返回给表单,使用onsubmit接收
    -->
    <form method="POST" action="http://www.baidu.com" onsubmit="return checkButton()">

        <p>
            <span>username:</span> <input type="text" id="username" required name="username">
        </p>

        <!--表面上的密码框-->
        <p>
            <span>pwd</span> <input type="password" id="password" required name="password">
        </p>

        <!--实际上把密码转移到了这里-->
        <input type="hidden" id="md5-pass" name="pass">

        <!--绑定事件 onclick 被点击-->
        <button type="submit">commit</button>
    </form>
    
    <script>
        //获取表单内容并进行检查
        function checkButton() {
            let uname = document.getElementById('username');
            let pwd = document.getElementById('password');
            let md5_pass = document.getElementById('md5-pass');

            pwd.value = md5(pwd.value);
            md5_pass.value = md5(pwd.value);

            //可以校验表单内容决定返回值,从而起到阻止提交的作用
            return true;
        }

    </script>
</body>
</html>

9. jQuery

jQuery库中存在大量的js函数

获取jQuery

  1. 从jQuery官网下载jQuery的js文件,然后直接导入到文件中

    jQuery

  2. 线上导入jQuery CDN

    jQuery cdn加速 (jq22.com)

    <!DOCTYPE html>
    
    <html>
        <head>
            <meta charset="UTF-8">
            <title>demo</title>
    
            <!--在线引入-->
            <script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
            
        </head>
    
        <body>
            
        </body>
    </html>
    

本地导入:

<!DOCTYPE html>

<html>
    <head>
        <meta charset="UTF-8">
        <title>demo</title>

        <script src="../jQuery.js"></script>
        
    </head>

    <body>
        <!--
            jQuery公式:   $(selector).action
            这里的选择器就是css的选择器
        -->

        <a href="#" id="test">点我</a>

        <script>
            $('#test').click(function(){
                alert('hello?');
            });

        </script>
    </body>
</html>

本来这段是写在cdn引入jQuery的里面的,但是发现cdn引入的时候没有起到作用,所以个人建议还是本地导入jQuery把

选择器

            //原生Js,选择器少而且写着麻烦
            document.getElementById();
            document.getElementsByTagName();
            document.getElementsByClassName();

            //对比jQuery选择器,css的选择器这里都可以用
            //API:  https://jquery.cuishifeng.cn/
            //标签选择器
            $('p').click();
            //标签选择器
            $('#test').click();
            //类选择器
            $('.class').click();

API: https://jquery.cuishifeng.cn/

jQuery事件

  • 鼠标事件

    主要是mouse打头的几个事件

    1. mousedown() 鼠标按下
    2. mouseenter()
    3. mouseleave() 鼠标离开
    4. mousemove() 鼠标移动
    5. mouseout()
    6. mouseover() 点击结束
    7. mouseup()

    常用的是按下和移动

  • 键盘事件

  • 其他事件

案例:获取鼠标位置

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>index</title>

        <script src="../jQuery.js"></script>

        <style>
            #divMove{
                width: 500px;
                height: 500px;
                border: 1px dashed orange;
            }
        </style>

    </head>
    <body>
        <!--要求: 获取鼠标当前的坐标-->
        mouse: <span id="mouseMove"></span>

        <div id="divMove">
            在这里移动鼠标试试
        </div>

        <script>
            //当网页元素加载完毕之后,相应事件
            //旧版操作: $(document).ready(function(){});
            //简化版:
            $(function(){
                //对div设置鼠标移动事件
                //function中的e参数指鼠标移动事件的值,e只是一个标识符,可以随便写
                $('#divMove').mousemove(function(e){
                    //用span的内容显示鼠标位置
                    $('#mouseMove').text('x: ' + e.pageX + 'y: ' + e.pageY);
                })
            }) 
        </script>
    </body>
</html>

操作DOM:

节点文本的操作:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>index</title>

        <script src="../jQuery.js"></script>
        

    </head>
    <body>

        <ul id="test-ul">
            <li class="js">Java</li>
            <li name="python">Python</li>
        </ul>
        
        <script>
            //操作文本内容
            //获得值
            $('#test-ul li[name=python]').text();
            $('#test-ul li[name=python]').html();
            //设值值
            $('#test-ul li[name=python]').text('this is python');
            $('#test-ul li[name=python]').html('this is python');
        
        </script>
            
    </body>
</html>

css的操作:

//css操作
$('test-ul li[name=python]').css({ "color": "#ff0011", "background": "blue" });

//元素的显示和隐藏
$('#py').hide();
$('#py').show();

元素显示隐藏的本质就是display:none

选中窗口

$(window).width();
$(window).height();

document

$(document).width();
$(document).height();

总结

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值