批改状态:合格
老师批语:
构造函数是一个创建对象的工厂,构造函数有一个属性叫prototype(原型),所有类实例共享的成员,都应该写到构造函数的原型上, 实例的原型永远指向它的构造函数的原型,实例的原型从构造函数的原型继承属性和方法,如果你new一个实例对象出来,在实例对象当中找不到一个属性,它会到原型上面去找,也就是实例的对象原型是继承自构造函数原型
function UserInfo(name,age){this.name=name;this.age=age;}
给构造函数原型添加一个原型属性:
UserInfo.prototype.national="China";
//用构造函数实例化一个对象:
const newUser = new UserInfo('小张',18);
给实例对象添加一个原型属性,它会指向它的构造函数的原型,也就是实例的对象原型是继承自构造函数:
newUser.__proto__.region="Guangdong";console.log(newUser.national,newUser.region);//China Guangdong
但是给实例对象添加一个和原型属性相同的属性名字,则会覆盖掉原型属性
newUser.region="Guangxi";console.log(newUser.national,newUser.region);//China Guangxi
1:传统的方式:
document.getElementById //ID选择器document.getElementsByClassName //类名选择器document.getElementsByName //name选择器document.getElementsByTagName //标签选择器
2:querySelector:返回匹配的元素集合中的第一个元素,(返回一个)
例如用querySelector操作以下html代码中第一个li:
<ul><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li></ul>
js代码如下:
li = document.querySelector("li");li.style.color="red";//如图第一个li变红了

3:querySelectorAll:返回匹配的元素集合所有成员
例如操作所有li的背景色:
ls=document.querySelectorAll("li");ls.forEach(element => {element.style.backgroundColor="red";});
1.基本语法:
1.1:创建元素使用:document.createElement(“要创建的元素”);
1.2:添加到页面:parent.appendChild(“要添加的新元素”);
1.3:html语句插入:parent.insertAdjacentHTML(“插入位置”,””插入的语句),有四种位置可以插:
| 语句 | 位置 |
|---|---|
| beforeBegin | 插入到标签开始前 |
| afterBegin | 插入到标签开始标记之后 |
| beforeEnd | 插入到标签结束标记前 |
| afterEnd | 插入到标签结束标记后 |
1.4:创建虚拟的节点对象document.createDocumentFragment();
1.5:元素插入:insertAdjacentElement(“插入位置”,””插入的元素);
1.6:更新:parentNode.replaceChild(newChild, oldChild);
1.7:移除:node.removeChild(child);
2.实战部分:
明白了基本语法,我们就可以实战一下:
以以下html为例:
<ul id="list"><li>items1</li><li>items2</li><li>items3</li><li>items4</li><li>items5</li><li>items6</li></ul>
const ul=document.querySelector("#list");const li=document.createElement("li");ul.appendChild(li);li.innerText="imNew";li.style.color="red";
或者可以试试新方法:
let str="<li>我是新来的</li>";ul.insertAdjacentHTML("beforeEnd",str);
效果如下:
let h4 = document.createElement("h4");h4.innerText="我是h4";document.querySelector("li:nth-of-type(1)").replaceWith(h4);
或者:
let changeChild = document.querySelector("li:first-of-type");ul.replaceChild(h4,changeChild);
效果如下:
let rem = document.querySelector("#list h4");ul.removeChild(rem);
好了,这下我们的h4不见了
4:js中dom的查询方法:
1.语法:
| 语句 | 说明 |
|---|---|
| .children | 获取所有子元素 |
| .firstElementChild | 获取第一个子元素: |
| .lastElementChild | 最后一个 |
| .parentElement | 获取元素的父亲 |
| .previousElementSibling | 获取前一个兄弟 |
| .nextElementSibling | 获取最后一个兄弟 |
例如我们要获取以下第三个li的最后一个兄弟元素的innerHTML内容:
<ul id="list"><li>items1</li><li>items2</li><li>items3</li><li>items4</li><li>items5</li><li>items6</li></ul><script>let li=document.querySelector("li:nth-of-type(3)");console.log(li.nextElementSibling.innerHTML);//items4</script>

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号