2.dataset
element.dataset.index;
element.dataset.listName; //data-list-name;
dataset["index"];
3.節點操作 node->更好的選擇節點
// nodeType,nodeName,nodeValue
node.parentNode;
parentNode.childNodes; //包括文字text 不提倡 nodeType==1 -> element
parentNode.children; //推薦
parentNode.firstChild; //第一個節點,可能是文字節點
parentNode.firstElementChild; //第一個元素 E9才有
parent.children[0];
parentNode.lastChild;
parent.children[parent.children.length - 1];
node.nextSibling; //包含text..
node.previousSibling;
node.nextElementSibling; //下一個兄弟元素節點 相容性
node.previousElementSibling; //上一個兄弟元素節點 nodeType===1為元素節點
建立節點;
document.createElement("tagName");
先建立在新增節點
:node.appendChild(child);//push
:node.insertBefore(child,element);
刪除節點:
node.removeChild(child);
複製節點:
node.cloneNode();//再插入,appendchild,insert; 括號為空||false為淺複製只複製節點不複製內容;
node.cloneNode(ture)
4.建立元素
document.write(); //重繪 不推薦
window.load = function () {
xxx;
};
innnerHtml; //字元拼接 用陣列可提高效率
createElement; //建立很多個時,快
5.DOM 核心 增刪改查
appenchild(child);
createelement("d");
removechild;
src, type, style;
getelementbyid;
getelementbyclassname;
getelementbytagname;
queryselector;
queryselectorall;
6.高階事件:
pageshow
e.persisted//true來自快取
1.註冊事件:
傳統:
<button onclick='alert("hi")'></button>
btn.onclick=function(){}
監聽://推薦
eventTarget.addEventListener(type,listener[,useCapture])//typeof type -> string ;usecapture=true為捕獲階段
attachEvent()//不推薦
2.刪除事件
傳統.onclick = null
.removeEventListener("click", fn)
.detachEvent("onclick", fn);
3.dom 事件流 :捕獲,目標,冒泡
js 中只能有捕獲或者冒泡階段
onclick,attchEvent 只能捕獲冒泡
onblur,onfoucus,onmouseenter.onmouseleave 沒有冒泡
4.事件物件
div.onclick = function (event) {
console.log(event || window.event);
};
e.target || window.event.srcElement; //觸發事件的物件
this; //繫結的物件
e.currentTarget; //ie678
e.type;
5.阻止預設行為:
e.preventDefault();
相容:e.returnValue;
return false;
6.防止冒泡:
e.stopPropagation
::e.cancelBuble=true
7.委託事件:
給父類新增事件監聽器,點選子類冒泡到父類
e.target.style...
8.Mouse:
docu.addEventListener("contextmenu", function (e) {
e.preventDefault();
});
selectstart;
mousemove;
e.clientX;
e.clientY;
e.pageX;
e.pageY;
e.screenX;
9.keyEvent:
onkeyup / down / press;
up / down不區分大小寫;
press區分但不識別功能鍵;
keyCode;
BOM
相容性差
全域性物件
1.window.onload(fn);以最後一個為準
2.window.add-L('DOMContentLoaded',fn);
3.window.(on)resize w.innerWidth;//當前螢幕寬度
4.定時器:
setTimeout //只執行一次
setTimeout(callback, 2000); //延遲事件毫秒;default:0
setTimeout("fn()", 2000); //不推薦
起名字:
var timer1=setTimeout(fn,2000);
stop:
window.clearTimeout(timer1)
setInterval(callback,[s]);//不斷呼叫
clearInterval(timer);
this 誰呼叫指向誰
5.同步與非同步
js 是單執行緒
console.log(1);
setTimeout(function () {
console.log(3);
}, 1000);
console.log(2);
//r:1,2,3
1.回撥函式屬於非同步任務->任務佇列
2.同步任務->主執行緒執行棧
3.js 程式碼執行流程:event loop
先同步再非同步
先執行棧再執行佇列
棧執行完後 佇列=true則將任務佇列放到執行棧後面執行
example
console.log(1);
setTimeout(function () {
console.log("end");
}, 0);
console.log(2);
6.location:url
url:protocol://host[:port]/path/ [?query] #fragment
| | | | |
location.href||host||port||pathname||search||hash||
l.assign();
l.replace();
l.reload([true]);
7.navaigator:userAgent
if (
navigator.userAgent.match(
/phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrower|JUC|Feenec|wOSBrower|BrowerNG|WebOS|Symbian|Windows Phone)/i
)
) {
windows.location.href = ""; //mobile
} else {
widows.location.href = ""; //pc
}
8.History
history.back();
history.forword();
history.go(1 | 2 | -1);
9.offset 偏移量
element.offsetParent;//return a fatherelement having a position
.offsetTop;
.offsetLeft;// 有無定位
.offsetWidth;//padding+border+margin; only_read
.offsetHeight;//no 單位
style 更適合修改值 //只能讀取行內元素
offset 更適合讀取值
10.client
element.clientTop; //上邊框
.clientLeft
.clientWidth
.clientHeight//不含邊框,不帶單位
11.立即執行函式:
優勢:獨立建立了一個作用域
1(function () {})();
2((function () {})());
12.Scroll
element.scrollTop; //返回被捲去的上側距離,不帶單位
element.scrollLeft;
element.scrollWidth; //返回實際高度,不含邊框
div.add - L("scroll", fn);
window.pageYOffset
13.mouseover||mouseenter
mouseover 子盒子也會觸發
mouseenter 不會冒泡,只會觸發自己的盒子
20.移動端:
1. touch
touchend
touchmove
touchstart
2.touchevent
touches/targetTouches/changedTouches
21.本地儲存
localstorage/sessionstorage
.setItem/.getItem/.clear()/removeItem(...)
22.js 閉包
<script>
function outer() {
let a = 1;
function fn() {
console.log(a);
}
return fn;
}
const f = outer();
//application
function cnt(){
let i=0;
function fn(){
i++;
console.log(i);
}
return fn;
}
let count=cnt();
count();
</script>
23.變數提升 var 才有
<script>
//只提升宣告,當前作用下 console.log(num + 'jj');//undefinedjj var num = 33;
</script>
函式也有提升,只提升宣告,不呼叫;
24.動態引數 arguments 偽陣列不能用陣列方法
function sum(e) {
let s = 0;
for (let index = 0; index < arguments.length; index++) {
s += arguments[index];
}
return s;
}
console.log(sum(1, 2));
console.log(sum(1, 2, 3, 4));
25.剩餘引數 ... 真陣列
<script>
function sum(...arr) {
let s=0;
arr.forEach(function(a){
s+=a;
})
return s;
}
console.log(sum(1,2));
console.log(sum(1,2,3,4));
</script>
26. ...arr 展開陣列
let arr1 = [1, 3, 4, 5, 6, 7];
let arr2 = [1, 3, 4, 5, 6, 7];
// ...arr1 === 1,3,5...
console.log(Math.max(...arr1));
console.log(Math.min(...arr2));
let arr = [...arr1, ...arr2];
27.=>函式
<script>
let fn=name=>({
name:name
})
console.log(fn('Alex'));//name:Alex
</script>
let sum = (...arr) => {
let s = 0;
arr.forEach((x) => (s += x));
return s;
};
console.log(sum(1, 2));
28.陣列結構
let a = 1;
let b = 2;
[a, b] = [b, a]; //a:2,b:1;
let [a = 0, b = 0] = [1, [2, 4]];
console.log(a);
console.log(b);
console.log(b[0]);
let [a2 = 0, [c, d]] = [1, [2, 4]];
console.log(c);
console.log(d);
let getvalue = () => [22, 55];
let [val1, val2] = getvalue();
console.log(val1);
29.物件結構:
const pig = {
name: "Aelx",
age: 3,
};
const { name: pigname, age } = pig;
console.log(pigname);
console.log(age);
const goods = [
{
goodsName: "huawei",
price: 1333,
manager: {
age: 33,
address: "beijing",
},
},
];
const [{ goodsName, price }] = goods;
console.log(goodsName);
console.log(price);
const [
{
manager: { age: myAge, address },
},
] = goods;
console.log(address);
function a({ data: myData }) {
return myData.xxx();
}
30.forEach
let arr = [1, 3, "red"];
arr.forEach(function (item, index) {
console.log(item);
console.log(index);
});
31.建構函式
//建構函式
// 1.首字母大寫 2.無return 3.new為例項化返回一個物件
function Goods(name, price, count) {
this.name = name;
this.price = price;
this.count = count;
}
const { name, price, count } = new Goods("xiaomi", "1999", 20);
console.log(name);
console.log(price);
console.log(count);
32.靜態/動態成員:
function Person(name, age) {
(this.name = name), (this.age = age);
//例項成員
}
const xm = new Person("xiaoming", 33);
console.log(xm.name); //例項屬性
xm.sayHi = () => {
console.log("xiaomign Hello");
}; //例項方法
Person.canwalk = true; //靜態屬性
Person.sayBye = () => {
console.log("byebye");
}; //靜態方法
Person.sayBye();
console.log(Person.canwalk);
33.包裝型別/引用型別
1.Object
let obj = {
name: "Alex",
age: 33,
};
const keys = Object.keys(obj);
const values = Object.values(obj);
console.log(keys);
console.log(values);
const obj2 = {};
Object.assign(obj2, obj);
console.log(obj2);
2.Array
Array 建立
let arr = new Array(1);
let arr2 = new Array(3);
console.log(arr); //[空]
console.log(arr.length); //1
console.log(arr[0]); //undefined
console.log(arr[1]); //undefined
console.log(arr2); //[空x3]
console.log(arr2.length); //3
1.reduce
const arr = [1, 2, 3];
let sum = arr.reduce((prev, current) => prev + current, 10);
console.log(sum);
const arr2 = [
{
name: "zhangsan",
salary: 1000,
},
{
name: "lisi",
salary: 333,
},
{
name: "wangwu",
salary: 222,
},
];
arr2.reduce((prev, current) => {
return prev + current.salary;
}, 0); //第三個引數不為零則預設陣列第一個元素
2.from(arr);
let lis = document.querySelectorAll("ul li"); //NodeList 偽陣列
console.log(lis);
let li = Array.from(lis); //轉Array
console.log(li);
li.pop();
console.log(li);
3.find(item=>item...)
let arr = [10, 20, 30];
let a = arr.find((item) => item > 10);
console.log(a); //20
let obj = [
{
name: "xiaomi",
price: 3333,
},
{
name: "huawei",
price: 9999,
},
];
let huaweiObj = obj.find((item) => item.name === "huawei");
console.log(huaweiObj); //{name: 'huawei',price: 9999}
4.at(-1)
34.原型
//公共屬性寫在建構函式里
//公共方法寫在原型裡
function Person(name, age) {
(this.name = name), (this.age = age);
//this 指向例項化物件
}
Person.prototype.sing = function () {
//this 指向例項化物件
console.log("singing...");
};
let ldh = new Person("liudehua", 33);
ldh.sing();
35.原型新增陣列函式:
const arr = [1, 2, 3];
Array.prototype.min = function (arr) {
return Math.min(...this);
};
Array.prototype.max = function (arr) {
return Math.max(...this);
};
Array.prototype.sum = function (arr) {
return this.reduce((prev, current) => prev + current, 0);
};
console.log(arr.min());
console.log(arr.max());
console.log(arr.sum());
36.constructor
function Person(name, age) {
(this.name = name), (this.age = age);
}
console.log(Person.prototype);
Person.prototype = {
constructor: Person,
sing: function () {
console.log("sing");
},
dance: function () {
console.log(dance);
},
};
console.log(Person.prototype.constructor === Person);
37.proto
function Person(name, age) {
(this.name = name), (this.age = age);
}
const xm = new Person("xm", 33);
//__proto__ -> [[Prototype]] js非標準屬性
console.log(xm.__proto__ === Person.prototype);
console.log(xm.constrctor === Person);
38.原型繼承
function Person() {
(this.eyes = 2), (this.head = 1);
}
function Woman() {}
Woman.prototype = new Person();
Woman.prototype.sing = function () {
console.log("sing");
};
let woman = new Woman();
woman.sing();
function Man() {}
Man.prototype = new Person();
// Man.prototype.sing = function () {
// console.log('sing');
// }
let man = new Man();
man.sing;
39.原型鏈
//原型鏈
//只要是物件就有__proto__,只要是原型就有constructor
function Person() {
(this.eyes = 2), (this.head = 1);
}
let p1 = new Person();
console.log(p1.eyes);
console.log(p1.__proto__);
console.log(Person.prototype);
console.log(Person.prototype.__proto__);
console.log(Person.prototype.__proto__ === Object.prototype);
console.log(Object.prototype.__proto__ === null);
console.log(Person instanceof Object);
40.deepcopy
//deepcopy copy
let obj1 = {
name: "Alex",
hobby: [1, "sing"],
family: {
father: "Mith",
},
};
let obj2 = obj1;
//共同用一個地址,你改變了他也改變,淺複製
console.log(obj2);
obj2.hobby[1] = "Obj2";
console.log(obj2);
console.log(obj1);
// deepcopy三種實現:1.自定義遞迴函式deepcp,2.loadlash:_.cloneDeep(obj),3.JSON.stringify
// function deepCopy(newObj,oldObj){
// if()
// }
let newobj = JSON.parse(JSON.stringify(obj1));
41.try/catch
let arr = [];
try {
let div = document.querySelector(".div");
function a() {}
} catch (error) {
debugger;
throw new Error("Error");
} finally {
console.log("finally");
}
console.log("after try");
42.this call bind apply
//this:call,apply,bind
//fn.call(thisArg,args*)
//fn.apply(thisArg,[Array])
//fn.bind(thisArg,args*) 不呼叫 return fn(this不同)
console.log(this); //window
function fn(x, y) {
console.log(this);
return x + y;
}
fn(); //window
const obj = {
name: "Alex",
};
let a = fn.call(obj, 1, 2); //log
console.log(a); //3
let b = fn.apply(obj, [1, 3]);
console.log(b); //4
let c = fn.bind(obj, 3, 5);
console.log(c);
console.log(c(4, 6)); //8
let d = fn.bind(obj);
console.log(c(4, 6)); //10