在 Web 开发中,动态地将 HTML 元素插入到页面里是一项基础且关键的技能。本文会深入剖析一段运用 DOM 操作插入 HTML 元素的代码,以 EditInPlace
函数为例,讲解其实现思路与代码逻辑。
代码示例
editInPlace.js 文件
kotlin
/**
*@func 初始化包含特定内容的元素
*@params {id,parent(父节点),value(默认值)}
*@author shuanyuan
*@date 2025-04-15
*/
function EditInPlace(id,parent,value) {
this.id=id;
this.parent=parent||document.body;
this.value=value||"这个家伙很懒,什么都没有留下";
this.createElement(this.id)
}
EditInPlace.prototype.createElement=function(id){
this.containerElement=document.createElement("div");
this.containerElement.id=id;
this.parent.appendChild(this.containerElement);
this.staticElement=document.createElement("span");
this.staticElement.innerHTML=this.value;
this.containerElement.appendChild(this.staticElement);
}
better.html 文件
xml
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>EditInPlace bilibili用户体验打造</title>
</head>
<body>
<div id="app">
</div>
<script src="./editInPlace.js"></script>
<script>
// 流程代码,走向面向对象封装
new EditInPlace(
'ep1',
document.getElementById('app')
)
</script>
</body>
</html>
代码详细解析
EditInPlace
构造函数
kotlin
function EditInPlace(id,parent,value) {
this.id=id;
this.parent=parent||document.body;
this.value=value||"这个家伙很懒,什么都没有留下";
this.createElement(this.id)
}
- 参数接收 :
EditInPlace
函数接收三个参数,分别是id
、parent
和value
。id
用于唯一标识元素;parent
是元素要插入的父节点,若未提供则默认使用document.body
;value
是要显示的默认内容,若未提供则使用预设的提示信息。 - 方法调用 :在构造函数内部调用
this.createElement(this.id)
方法,开始创建并插入 HTML 元素。
createElement
原型方法
javascript
kotlin
EditInPlace.prototype.createElement=function(id){
this.containerElement=document.createElement("div");
this.containerElement.id=id;
this.parent.appendChild(this.containerElement);
this.staticElement=document.createElement("span");
this.staticElement.innerHTML=this.value;
this.containerElement.appendChild(this.staticElement);
}
- 创建
div
容器 :运用document.createElement("div")
创建一个div
元素,将其作为容器,并通过this.containerElement.id = id
为其设置id
。接着使用this.parent.appendChild(this.containerElement)
把div
元素插入到指定的父节点中。 - 创建
span
元素 :使用document.createElement("span")
创建一个span
元素,借助this.staticElement.innerHTML = this.value
设置其显示内容。最后使用this.containerElement.appendChild(this.staticElement)
把span
元素添加到div
容器里。
better.html 文件中的调用
xml
<script>
new EditInPlace(
'ep1',
document.getElementById('app')
)
</script>
在 HTML 文件中,通过 new
关键字实例化 EditInPlace
对象,传入 id
和父节点元素,从而触发元素的创建与插入操作。
总结
通过上述代码,我们清晰地看到如何利用 JavaScript 的构造函数和原型方法,结合 DOM 操作来动态插入 HTML 元素。这种方式在需要根据用户交互或数据动态生成页面内容时非常实用,能够极大地提升页面的灵活性与交互性。