Warning: error_log(/data/www/wwwroot/hmttv.cn/caches/error_log.php): failed to open stream: Permission denied in /data/www/wwwroot/hmttv.cn/phpcms/libs/functions/global.func.php on line 537 Warning: error_log(/data/www/wwwroot/hmttv.cn/caches/error_log.php): failed to open stream: Permission denied in /data/www/wwwroot/hmttv.cn/phpcms/libs/functions/global.func.php on line 537
avaScript對象分類
BOM瀏覽器對象模型
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)
//只執行一次
setTimeout(function () {
alert("時間到")
},5000)
</script>
DOM文檔對象模型
包含和頁面元素相關的內容
<input type="text" id="i1">
<input type="button" value="飛機" 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="請輸入數字"
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>
//通過標簽名獲取table
let table=document.querySelector("table");
function f() {
//創建 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 裝進table
table.append(trs);
}
</script>
什么是 JSON?
【注】JSON 使用 JavaScript 語法,但是 JSON 格式僅僅是一個文本。文本可以被任何編程語言讀取及作為數據格式傳遞。
//json實例
{"sites":[
{"name":"Runoob", "url":"www.runoob.com"},
{"name":"Google", "url":"www.google.com"},
{"name":"Taobao", "url":"www.taobao.com"}
]}
JSON 語法規則
JSON 對象
JSON 對象保存在大括號內。
//就像在 JavaScript 中, 對象可以保存多個 鍵/值 對:
{"name":"Wong", "url":"www.celinf.cn"}
JSON函數
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 的例子。當用戶改變輸入字段的內容時,會調用 upperCase() 函數。
<input type="text" id="fname" onchange="upperCase()">
練習Demo
<table border="1">
<caption>個人信息</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="請求數據" 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>
學習記錄,如有侵權請聯系刪除
提供當前窗口中的加載的文檔有關的信息和一些導航功能。 既是 window 對象屬性,也是 document 的對象屬性
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=// 頁面的標準域名
'www.zhihu.com'.hash=// 服務器名稱+端口 例如:‘www.zhihu.com:8080’
'#hash'.pathname=// url中#號后面的哈希值
'/search'.search=// url中[/]后面內容
'?type=content&q=123'.protocol=// url中[?]后面內容
'https:'.port=// 協議[http:]
''; //端口號:[ 80 | 8080 | ... ]
方法:
history.state.length; // 當前頁面的狀態 // 返回當前 `會話` 中的 history 個數
方法:
相關聯的方法
例子:
window.onpopstate=function (event) {
alert(
'location: ' +
document.location +
', state: ' +
JSON.stringify(event.state),
);
};
//綁定事件處理函數.
history.pushState({ page: 1 }, 'title 1', '?page=1'); //添加并激活一個歷史記錄條目 http://example.com/example.html?page=1,條目索引為1
history.pushState({ page: 2 }, 'title 2', '?page=2'); //添加并激活一個歷史記錄條目 http://example.com/example.html?page=2,條目索引為2
history.replaceState({ page: 3 }, 'title 3', '?page=3'); //修改當前激活的歷史記錄條目 http://ex..?page=2 變為 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}
瀏覽器系統信息大集合
用來表示瀏覽器窗口外部的顯示器的信息等
window.screen.deviceXDPI/deviceYDPI 屏幕實際的水平 DPI、垂直 DPI
瀏覽器事件模型主要分為三個階段:
el.addEventListener(event, function, useCapture)
// useCapture默認值false,也就是默認冒泡
// 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') {
// 業務邏輯...
e.target.style.backgroundColor='pink';
}
}
list.addEventListener('click', onClick, false);
先區別 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 請求
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事件可以報告長時間運行的文件上傳
xhr.upload.onprogress=(p)=> {
console.log(Math.round((p.loaded / p.total) * 100) + '%');
};
});
}
// resolve若發生在網絡通信正常(404,500)也是resolve
fetch('http://domain/service', {
method: 'GET',
})
.then((response)=> {
// 想要精確的判斷 fetch是否成功
// 需要包含 promise resolved 的情況,此時再判斷 response.ok是不是為 true
if (response.ok) {
return response.json();
}
throw new Error('Network response was not ok.');
})
.then((json)=> console.log(json))
// .catch()也不會被執行
.catch((error)=> console.error('error:', error));
// ************************************
// 不支持直接設置超時, 可以用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中斷請求
const controller=new AbortController();
// AbortController接口表示一個控制器對象
// 允許你根據需要中止一個或多個 Web請求
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 客戶端錯誤|500 服務器錯誤
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();
});
};
端瀏覽器對象模型BOM常用對象介紹,BOM即Broswer Object Model 瀏覽器對象模型,在JavaScript中可以理解為window對象,用來進行與瀏覽器相關的一些操作,學習BOM就是學習 JavaScript中的window對象。
一、window對象
BOM的核心對象是 window,它代表瀏覽器的一個實例。在瀏覽器中,window有著雙重的角色:JavaScript訪問瀏覽器的接口對象,ES中的Global對象意味著網頁中的任何一個對象,變量,函數都是以window作為其Global對象。
1、全局作用域,在ECMAScript中,window對象扮演著Global對象的角色,也就是說,所有在全局作用域聲明的變量,函數都會變成window的屬性和方法,都可以通過 window.屬性名(或方法名) 直接調。
2、導航和打開窗口,通過 window.open() 既可以導航到一個特定的URL,也可以打開一個新的瀏覽器窗口
二、location對象
[^location 是最有用的BOM對象之一,它提供了與當前窗口中加載的文檔有關的信息]: JavaScript高級程序設計。
注: window.location 和 document.location?引用的是同一個對象。location 既是 window 對象的屬性,也是 document?對象的屬性。
三、 navigator對象
navigator 對象主要用來獲取瀏覽器的屬性,區分瀏覽器類型;
navigator 對象屬性較多,且兼容性比較復雜。
四、history對象
history 對象保存著用戶上網的歷史記錄,從窗口被打開的那一刻算起,因為 history 是 window 對象的屬性,因此每個瀏覽器窗口,每個標簽乃至每個框架,都有自己的 history對象與特定的 window 對象關聯。
總結瀏覽器對象模型BOM中常用的對象有navigator,window, location, history
window既是 JavaScript 的全局對象,也是BOM的一個實例,所有的全局方法,屬性,BOM中的屬性,都可以通過 window. 來調用;
window作為BOM的實例,最常用的幾個方法分別是:window.open(),window.close(),,分別用來打開和關閉瀏覽器窗口頁面,這里需要注意的是,通過 open 方法打開的頁面,才能通過close 方法關閉;
location對象也是用的比較多的一個BOM對象,主要用來操作URL相關的一些信息,除了修改 Hash 之外的任何屬性,頁面都會重新加載,歷史記錄會多加一條歷史記錄;
location對象還有一個 reload() 方法用于手動重新加載頁面,該方法接收一個可選參數,為 true 的時候表示從服務器重新加載,否則可能從瀏覽器緩存中重新加載頁面;
location對象 還有一個比較特殊的方法,location.replace(),該方法可以覆蓋當前頁面并重新加載,同時不會在 history 中生成歷史記錄;
navigator對象主要用來獲取瀏覽器相關的一些信息,使用的時候需要注意兼容性。可以用來獲取瀏覽器類(Chrome,safrai,FireFox,Edge,IE)等;
history對象主要用來操作瀏覽器URL的歷史記錄,可以通過參數向前,向后,或者向指定URL跳轉。可以通過 length 屬性獲取記錄數,判斷當前頁面是否是打開的首個頁面;
*請認真填寫需求信息,我們會在24小時內與您取得聯系。