JavaScript 如何动态添加HTML元素
在本文中,我们将学习如何使用JavaScript动态添加HTML元素。需要基本了解HTML、CSS和Javascript。在这个示例中,我们将使用一个按钮,通过点击该按钮,我们可以动态添加HTML元素。
方法: 创建一个HTML文件,任意命名(如index.html),然后编写外部HTML模板,并添加一个按钮,当有人点击按钮时,HTML元素将以列表的形式动态添加。我们给按钮附加了一个onclick事件监听器,当有人点击按钮时,立即触发事件并执行与该事件监听器附加的回调函数。在回调函数中,我们需要指定希望在点击事件后发生的某个任务。
示例: 以下是上述方法的实现:
HTML
<!DOCTYPE html>
<html>
<head>
<style>
h1 {
color: green;
display: flex;
justify-content: center;
}
#mybutton {
display: block;
margin: 0 auto;
}
#innerdiv {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
</style>
</head>
<body>
<h1>
GeeksforGeeks
</h1>
<div id="innerdiv"></div>
<button id="mybutton">
click me
</button>
<script>
document.getElementById("mybutton").
addEventListener("click", function () {
document.getElementById("innerdiv").
innerHTML += "<h3>Hello geeks</h3>";
});
</script>
</body>
</html>
输出:
示例2: 在这个示例中,我们将看到使用appendChild()方法。
HTML
<!DOCTYPE html>
<html>
<head>
<style>
h1 {
color: green;
display: flex;
justify-content: center;
}
#mybutton {
display: block;
margin: 0 auto;
}
div {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
</style>
</head>
<body>
<h1>
GeeksforGeeks
</h1>
<div id="innerdiv"></div>
<button onclick="mybutton()" id="mybutton">Click Me</button>
<script>
function mybutton() {
const para = document.createElement("div");
para.innerText = "Hello Geeks";
document.body.appendChild(para);
}
</script>
</body>
</html>
输出: