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小时内与您取得联系。