如何实现输入框值追加到指定HTML标签而非覆盖?
解决提交内容覆盖问题的方案
问题核心是你当前用innerHTML = 新值直接替换了原有内容,要实现追加,只需要把赋值操作改成追加拼接,同时可以添加分隔元素让内容更易读。
修改后的核心逻辑
把原function2函数改成这样:
function function2(){ var a = document.getElementById('id2').value; var b = document.getElementById('textarea_text').value; // 跳过空内容提交 if(!a.trim() || !b.trim()) return; // 追加主题,用h3区分多个主题 document.getElementById("addh2_in_col1").innerHTML += `<h3>${a}</h3>`; // 追加问题,添加分隔线区分不同提问 document.getElementById('addp_in_col1').innerHTML += `<p>${b}</p><hr>`; // 提交后清空输入框,避免重复提交 document.getElementById('id2').value = ''; document.getElementById('textarea_text').value = ''; }
完整修改后的代码
<html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title></title> </head> <body> <style> #h1a{ background: rgb(2,0,36); background: linear-gradient(90deg, rgba(2,0,36,1) 0%, rgba(9,121,120,1) 37%, rgba(0,212,255,1) 100%); color: white; } button{ background-color: #0099ff; height: 48px; width: 200px; } #id1{ height: 45px; width: 200px; } * { box-sizing: border-box; } /* Create two equal columns that floats next to each other */ .column { float: left; width: 50%; padding: 10px; height: 300px; } /* Clear floats after the columns */ .row:after { content: ""; display: table; clear: both; } textarea{ width: 250px; height: 100px; } /* 新增样式优化追加内容的排版 */ .div-2 h3 { margin: 10px 0 5px; color: #0099ff; } .div-2 hr { border: none; border-top: 1px solid #eee; margin: 15px 0; } </style> <script> function function2(){ var a = document.getElementById('id2').value; var b = document.getElementById('textarea_text').value; // 过滤空提交 if(!a.trim() || !b.trim()) return; // 追加主题和问题,添加结构和分隔 document.getElementById("addh2_in_col1").innerHTML += `<h3>${a}</h3>`; document.getElementById('addp_in_col1').innerHTML += `<p>${b}</p><hr>`; // 清空输入框 document.getElementById('id2').value = ''; document.getElementById('textarea_text').value = ''; } </script> <div class="row"> <h1 id="h1a">Discussion Portal</h1> <div class="column"> <button>New Question Form</button> <input id="id1" type="text" placeholder="search questions..." ><br> <div class="div-2"> <h2 id='addh2_in_col1'></h2> <p id='addp_in_col1'></p> </div> </div> <div class="column"> <h1>Welcome to Discussion Portal</h1> <p>Enter a subject and question to get started</p><br> <input id="id2" type="text" placeholder="subject" ><br><br><br> <textarea id="textarea_text" placeholder="Question"></textarea><br> <input type="submit" value="Submit" onclick="function2()"> </div> </div> </body> </html>
修改说明
- 将
innerHTML =改为innerHTML +=,实现内容追加而非替换 - 增加空内容过滤逻辑,避免提交无效的空主题或问题
- 用
<h3>和<p>包裹新增内容,添加<hr>分隔线,让多个提问的排版更清晰 - 提交后自动清空输入框,优化用户操作体验
- 新增少量CSS样式,提升追加内容的视觉效果
内容的提问来源于stack exchange,提问作者Rajat Sedha
相关产品推荐
相关产品推荐

