
正如摘要所述,我们将通过修改 DOM 元素,动态创建和添加换行符和文本节点来实现这个效果,并对数值累加进行处理。
以下是一个完整的代码示例,演示了如何在按钮点击时动态添加换行和内容:
<!DOCTYPE html>
<html>
<head>
<title>动态添加换行和内容</title>
</head>
<body>
<p>Nombre:</p>
<input type="text" id="nombre">
<br>
<p>Monto:</p>
<input type="number" id="monto">
<br>
<button onclick="ir()">Enviar</button>
<br>
<p>Total: <span id="final">0</span> </p>
<div id="total">
</div>
<p>A cada uno le toca aportar: <span id="aporte">0</span></p>
<script>
function ir() {
const nombre = document.getElementById("nombre").value;
let monto = document.getElementById("monto").value;
const total = document.getElementById("total");
const final = document.getElementById("final");
const aporte = document.getElementById("aporte");
const lineBreak = document.createElement("br");
const newTotal = document.createTextNode(` ${nombre} : ${monto} `);
total.appendChild(lineBreak);
total.appendChild(newTotal);
monto = Number(monto) + Number(final.innerHTML);
final.innerHTML = `${monto}`;
aporte.innerHTML = `${monto}`;
};
</script>
</body>
</html>本文介绍了如何使用 JavaScript 在按钮点击时动态添加换行和内容。通过创建和添加 DOM 元素,可以实现灵活的页面内容更新。同时,需要注意类型转换、DOM 操作性能和安全性等问题,以确保代码的正确性和效率。
以上就是使用 JavaScript 在按钮点击时动态添加换行和内容的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号