栗子:
<style>
* {
margin: 0;
padding: 0;
}
#box div{
width: 100px;
height: 100px;
background: pink;
}
#box p {
width: 100px;
height: 100px;
background: cornflowerblue;
}
</style>
<body>
<div id="box">
<div></div>
</div>
</body>
JS操作:
操作1:
<script>
window.onload = function () {
const div = box.children[0];
div.onclick = function () {
console.log('div'); // 点击div控制台输出 div
};
/*box.innerHTML += `<p></p>` // 加上这条语句再点击div 。控制台没输出div*/
/*document.onclick = function () {
console.log('document'); // 点击div,输出 div、document*/
/*box.innerHTML += `<p></p>`
document.onclick = function () {
console.log('document');
}; */// 点击div,只输出 document
// 上述情况出现的原因
/*console.log(box.innerHTML); // 输出 div标签
console.log(typeof box.innerHTML); // string,是字符串,取出的是一串符号*/
};
</script>
box.innerHTML += <p></p>
相当于 box.innerHTML = <div></div>
+ <p></p>
那么 box.innerHtml 是字符串,而不再是标签,
且覆盖了之前的 div标签,那么之前的div标签就不存在了
也就获取不到div标签的点击事件了
操作2:
<script>
window.onload = function () {
const div = box.children;
box.innerHTML += `<p></p>`
div[0].onclick = function () {
// 设置的是修改后的 div 点击事件,上面设置的是 原来的div点击事件
console.log('div');
};
document.onclick = function () {
console.log('document');
};
};
// 输出 div document
</script>
createElement
在JS 创建一个标签元素,在Element中查看不到
暂存在JS 中,没有在页面上渲染出来
const p = document.createElement('p');
console.log(p); // 输出p标签,但没在页面上渲染出来
将p标签放到页面上
<script>
window.onload = function () {
const p = document.createElement('p');
p.id = 'p1';
p.className = 'p2';
p.onclick = function () {
alert('p');
};
box.appendChild(p); // 把标签放到页面上
};
</script>
这样操作的好处是 不会覆盖(删除)掉之前的div
文档片段(createDocumentFragment)
为解决createChild时,多次渲染页面,可创建一个文档片段
<script>
window.onload = function () {
const p = document.createElement('p');
const p1 = document.createElement('p');
// 创建文档片段
const domFrag = document.createDocumentFragment();
p.id = 'p1';
p.className = 'p2';
p.onclick = function () {
alert('p');
};
domFrag.appendChild(p);
domFrag.appendChild(p1);
box.appendChild(domFrag);
};
</script>
appendChild
在末尾添加
在原生JS中
没有在最前和特定位置添加的方法