avaScript對(duì)象分類
BOM瀏覽器對(duì)象模型
location位置
history歷史
<h1>0</h1>
<h2>0</h2>
<script>
setInterval(f,1000);
let i=document.querySelector("h1");
let count=0;
function f() {
count++;
i.innerText=count;
}
let num=0;
let j=document.querySelector("h2");
let timer=setInterval(function () {
num++;
j.innerText=num;
if(num==50){
clearInterval(timer)
}
},200)
//只執(zhí)行一次
setTimeout(function () {
alert("時(shí)間到")
},5000)
</script>
DOM文檔對(duì)象模型
包含和頁(yè)面元素相關(guān)的內(nèi)容
<input type="text" id="i1">
<input type="button" value="飛機(jī)" onclick="f(1)">
<input type="button" value="炸彈" onclick="f(2)">
<script>
let num=document.querySelector("#i1");
function f(x) {
if(isNaN(num.value)){
let error=document.createElement("div");
error.innerText="請(qǐng)輸入數(shù)字"
document.body.appendChild(error)
return;
}
let imgNum=x==1?"../airplane.png":"../bom3.png";
for(i=0;i<num.value;i++){
let computer=document.createElement("img");
computer.src=imgNum;
document.body.append(computer);
}
}
</script>
//======--------------=========<input type="text" id="i1" placeholder="姓名">
<input type="text" id="i2" placeholder="工資">
<input type="text" id="i3" placeholder="工作">
<input type="button" value="添加" onclick="f()">
<table border="1">
<tr>
<th>姓名</th>
<th>工資</th>
<th>工作</th>
</tr>
</table>
<script>
//通過標(biāo)簽名獲取table
let table=document.querySelector("table");
function f() {
//創(chuàng)建 tr 和td
let trs=document.createElement("tr")
let td_name=document.createElement("td")
let td_salary=document.createElement("td")
let td_work=document.createElement("td")
td_name.innerText=i1.value;
td_salary.innerText=i2.value;
td_work.innerText=i3.value;
//td 裝入 tr
trs.append(td_name,td_salary,td_work);
//tr 裝進(jìn)table
table.append(trs);
}
</script>
什么是 JSON?
【注】JSON 使用 JavaScript 語(yǔ)法,但是 JSON 格式僅僅是一個(gè)文本。文本可以被任何編程語(yǔ)言讀取及作為數(shù)據(jù)格式傳遞。
//json實(shí)例
{"sites":[
{"name":"Runoob", "url":"www.runoob.com"},
{"name":"Google", "url":"www.google.com"},
{"name":"Taobao", "url":"www.taobao.com"}
]}
JSON 語(yǔ)法規(guī)則
JSON 對(duì)象
JSON 對(duì)象保存在大括號(hào)內(nèi)。
//就像在 JavaScript 中, 對(duì)象可以保存多個(gè) 鍵/值 對(duì):
{"name":"Wong", "url":"www.celinf.cn"}
JSON函數(shù)
var text='{ "sites" : [' +
'{ "name":"celinf" , "url":"www.celinf.com" },' +
'{ "name":"Google" , "url":"www.google.com" },' +
'{ "name":"Taobao" , "url":"www.taobao.com" } ]}';
obj=JSON.parse(text);
document.getElementById("demo").innerHTML=obj.sites[1].name + " " + obj.sites[1].url;
HTML 事件屬性
//使用 onchange 的例子。當(dāng)用戶改變輸入字段的內(nèi)容時(shí),會(huì)調(diào)用 upperCase() 函數(shù)。
<input type="text" id="fname" onchange="upperCase()">
練習(xí)Demo
<table border="1">
<caption>個(gè)人信息</caption>
<tr>
<td>照片</td>
<td><img src="head.jpg" width="50px" alt="" id="head_img"></td>
</tr>
<tr>
<td>名字:</td>
<td id="name_td">XXX</td>
</tr>
<tr>
<td>年齡:</td>
<td id="age_td">XXX</td>
</tr>
<tr>
<td>好友</td>
<td>
<ul id="firend_ul">
</ul></td>
</tr>
</table>
<input type="button" value="請(qǐng)求數(shù)據(jù)" onclick="f()">
<script>
let person={name:"張三",url:"../bee.png",age:20,friend:["李四","王五","趙六"]}
function f() {
head_img.src=person.url;
name_td.innerText=person.name;
age_td.innerText=person.age;
for (let p of person.friend) {
let li=document.createElement("li")
li.innerText=p;
firend_ul.append(li)
}
}
</script>
學(xué)習(xí)記錄,如有侵權(quán)請(qǐng)聯(lián)系刪除
提供當(dāng)前窗口中的加載的文檔有關(guān)的信息和一些導(dǎo)航功能。 既是 window 對(duì)象屬性,也是 document 的對(duì)象屬性
window.location===document.location; //true
// https://www.zhihu.com/search?type=content&q=123
location.href='https://www.zhihu.com/search?type=content&q=123'.origin=// 完整的url
'https://www.zhihu.com'.host=// 頁(yè)面的標(biāo)準(zhǔn)域名
'www.zhihu.com'.hash=// 服務(wù)器名稱+端口 例如:‘www.zhihu.com:8080’
'#hash'.pathname=// url中#號(hào)后面的哈希值
'/search'.search=// url中[/]后面內(nèi)容
'?type=content&q=123'.protocol=// url中[?]后面內(nèi)容
'https:'.port=// 協(xié)議[http:]
''; //端口號(hào):[ 80 | 8080 | ... ]
方法:
history.state.length; // 當(dāng)前頁(yè)面的狀態(tài) // 返回當(dāng)前 `會(huì)話` 中的 history 個(gè)數(shù)
方法:
相關(guān)聯(lián)的方法
例子:
window.onpopstate=function (event) {
alert(
'location: ' +
document.location +
', state: ' +
JSON.stringify(event.state),
);
};
//綁定事件處理函數(shù).
history.pushState({ page: 1 }, 'title 1', '?page=1'); //添加并激活一個(gè)歷史記錄條目 http://example.com/example.html?page=1,條目索引為1
history.pushState({ page: 2 }, 'title 2', '?page=2'); //添加并激活一個(gè)歷史記錄條目 http://example.com/example.html?page=2,條目索引為2
history.replaceState({ page: 3 }, 'title 3', '?page=3'); //修改當(dāng)前激活的歷史記錄條目 http://ex..?page=2 變?yōu)?http://ex..?page=3,條目索引為3
history.back(); // 彈出 "location: http://example.com/example.html?page=1, state: {"page":1}"
history.back(); // 彈出 "location: http://example.com/example.html, state: null
history.go(2); // 彈出 "location: http://example.com/example.html?page=3, state: {"page":3}
瀏覽器系統(tǒng)信息大集合
用來表示瀏覽器窗口外部的顯示器的信息等
window.screen.deviceXDPI/deviceYDPI 屏幕實(shí)際的水平 DPI、垂直 DPI
瀏覽器事件模型主要分為三個(gè)階段:
el.addEventListener(event, function, useCapture)
// useCapture默認(rèn)值false,也就是默認(rèn)冒泡
// true為捕獲階段
{
/*
<ul class="list">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
*/
}
var list=document.querySelector('list');
function onClick(e) {
var e=e || window.event;
if (e.target.tagName.toLowerCase()==='li') {
// 業(yè)務(wù)邏輯...
e.target.style.backgroundColor='pink';
}
}
list.addEventListener('click', onClick, false);
先區(qū)別 IE 的不同之處
class BindEvent {
constructor(el) {
this.el=el;
}
addEventListener(type, handler) {
if (this.el.addEventListener) {
this.el.addEventListener(type, handler, false);
} else if (this.el.attachEvent) {
this.el.attachEvent('on' + type, handler);
} else {
this.el['on' + type]=handler;
}
}
removeEventListener(type, handler) {
if (this.el.removeEventListener) {
this.el.removeEventListener(type, handler, false);
} else if (this.el.detachEvent) {
this.el.detachEvent('on' + type, handler);
} else {
this.el['on' + type]=null;
}
}
static stopPropagation() {
if (e.stopPropagation) {
e.stopPropagation();
} else {
e.cancelBubble=true;
}
}
static preventDefault() {
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue=false;
}
}
}
封裝 XMLHttpRequest 請(qǐng)求
function ajax({ method='get', url='', params=undefined }) {
return new Promise((resolve, reject)=> {
let xhr=new XMLHttpRequest();
if (method.toLowerCase()==='get' && params !==undefined) {
url=url + '?' + params;
}
xhr.open(method, url, true);
xhr.onreadystatechange=function () {
if (xhr.readyState===4) {
if (xhr.status===200) {
resolve(xhr.responseText);
} else {
reject(xhr.status);
}
}
};
if (method.toLocaleLowerCase()==='get') {
xhr.send();
} else {
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(params);
}
xhr.onerror=(err)=> reject(err);
xhr.timeout=()=> reject('timeout');
// progress事件可以報(bào)告長(zhǎng)時(shí)間運(yùn)行的文件上傳
xhr.upload.onprogress=(p)=> {
console.log(Math.round((p.loaded / p.total) * 100) + '%');
};
});
}
// resolve若發(fā)生在網(wǎng)絡(luò)通信正常(404,500)也是resolve
fetch('http://domain/service', {
method: 'GET',
})
.then((response)=> {
// 想要精確的判斷 fetch是否成功
// 需要包含 promise resolved 的情況,此時(shí)再判斷 response.ok是不是為 true
if (response.ok) {
return response.json();
}
throw new Error('Network response was not ok.');
})
.then((json)=> console.log(json))
// .catch()也不會(huì)被執(zhí)行
.catch((error)=> console.error('error:', error));
// ************************************
// 不支持直接設(shè)置超時(shí), 可以用promise
function fetchTimeout(url, init, timeout=3000) {
return new Promise((resolve, reject)=> {
fetch(url, init).then(resolve).catch(reject);
setTimeout(reject, timeout);
});
}
// ************************************
// 中止fetch
// signal用于支持AbortController中斷請(qǐng)求
const controller=new AbortController();
// AbortController接口表示一個(gè)控制器對(duì)象
// 允許你根據(jù)需要中止一個(gè)或多個(gè) Web請(qǐng)求
fetch('http://domain/service', {
method: 'GET',
signal: controller.signal,
})
.then((response)=> response.json())
.then((json)=> console.log(json))
.catch((error)=> console.error('Error:', error));
controller.abort();
100 信息性|200 成功|300 重定向|400 客戶端錯(cuò)誤|500 服務(wù)器錯(cuò)誤
const request=(url)=> {
let resolved=false;
let t=1;
return new Promise((resolve, reject)=> {
// Promise.race([
// fetch(url),
// wait(100, ()=> fetch(url)),
// wait(200, ()=> fetch(url)),
// wait(400, ()=> fetch(url)),
// wait(800, ()=> fetch(url)),
// wait(1600, ()=> fetch(url)),
// ])
function doFetch() {
if (resolved || t > 16) return;
fetch(url)
.then((resp)=> resp.text())
.then((data)=> {
if (!resolved) {
resolved=true;
resolve(data);
}
});
setTimeout(()=> {
doFetch();
t *=2;
}, t * 100);
}
doFetch();
});
};
端瀏覽器對(duì)象模型BOM常用對(duì)象介紹,BOM即Broswer Object Model 瀏覽器對(duì)象模型,在JavaScript中可以理解為window對(duì)象,用來進(jìn)行與瀏覽器相關(guān)的一些操作,學(xué)習(xí)BOM就是學(xué)習(xí) JavaScript中的window對(duì)象。
一、window對(duì)象
BOM的核心對(duì)象是 window,它代表瀏覽器的一個(gè)實(shí)例。在瀏覽器中,window有著雙重的角色:JavaScript訪問瀏覽器的接口對(duì)象,ES中的Global對(duì)象意味著網(wǎng)頁(yè)中的任何一個(gè)對(duì)象,變量,函數(shù)都是以window作為其Global對(duì)象。
1、全局作用域,在ECMAScript中,window對(duì)象扮演著Global對(duì)象的角色,也就是說,所有在全局作用域聲明的變量,函數(shù)都會(huì)變成window的屬性和方法,都可以通過 window.屬性名(或方法名) 直接調(diào)。
2、導(dǎo)航和打開窗口,通過 window.open() 既可以導(dǎo)航到一個(gè)特定的URL,也可以打開一個(gè)新的瀏覽器窗口
二、location對(duì)象
[^location 是最有用的BOM對(duì)象之一,它提供了與當(dāng)前窗口中加載的文檔有關(guān)的信息]: JavaScript高級(jí)程序設(shè)計(jì)。
注: window.location 和 document.location?引用的是同一個(gè)對(duì)象。location 既是 window 對(duì)象的屬性,也是 document?對(duì)象的屬性。
三、 navigator對(duì)象
navigator 對(duì)象主要用來獲取瀏覽器的屬性,區(qū)分瀏覽器類型;
navigator 對(duì)象屬性較多,且兼容性比較復(fù)雜。
四、history對(duì)象
history 對(duì)象保存著用戶上網(wǎng)的歷史記錄,從窗口被打開的那一刻算起,因?yàn)?history 是 window 對(duì)象的屬性,因此每個(gè)瀏覽器窗口,每個(gè)標(biāo)簽?zāi)酥撩總€(gè)框架,都有自己的 history對(duì)象與特定的 window 對(duì)象關(guān)聯(lián)。
總結(jié)瀏覽器對(duì)象模型BOM中常用的對(duì)象有navigator,window, location, history
window既是 JavaScript 的全局對(duì)象,也是BOM的一個(gè)實(shí)例,所有的全局方法,屬性,BOM中的屬性,都可以通過 window. 來調(diào)用;
window作為BOM的實(shí)例,最常用的幾個(gè)方法分別是:window.open(),window.close(),,分別用來打開和關(guān)閉瀏覽器窗口頁(yè)面,這里需要注意的是,通過 open 方法打開的頁(yè)面,才能通過close 方法關(guān)閉;
location對(duì)象也是用的比較多的一個(gè)BOM對(duì)象,主要用來操作URL相關(guān)的一些信息,除了修改 Hash 之外的任何屬性,頁(yè)面都會(huì)重新加載,歷史記錄會(huì)多加一條歷史記錄;
location對(duì)象還有一個(gè) reload() 方法用于手動(dòng)重新加載頁(yè)面,該方法接收一個(gè)可選參數(shù),為 true 的時(shí)候表示從服務(wù)器重新加載,否則可能從瀏覽器緩存中重新加載頁(yè)面;
location對(duì)象 還有一個(gè)比較特殊的方法,location.replace(),該方法可以覆蓋當(dāng)前頁(yè)面并重新加載,同時(shí)不會(huì)在 history 中生成歷史記錄;
navigator對(duì)象主要用來獲取瀏覽器相關(guān)的一些信息,使用的時(shí)候需要注意兼容性。可以用來獲取瀏覽器類(Chrome,safrai,FireFox,Edge,IE)等;
history對(duì)象主要用來操作瀏覽器URL的歷史記錄,可以通過參數(shù)向前,向后,或者向指定URL跳轉(zhuǎn)。可以通過 length 屬性獲取記錄數(shù),判斷當(dāng)前頁(yè)面是否是打開的首個(gè)頁(yè)面;
*請(qǐng)認(rèn)真填寫需求信息,我們會(huì)在24小時(shí)內(nèi)與您取得聯(lián)系。