如何用for循环获取编号用户输入并写入新页面?
解决动态输入框内容获取与写入问题
现有代码的问题
- 你现在的代码把DOM元素本身push进了数组,而不是输入框里的内容,得取
currentVar.value才对 - 函数没有返回存储好的列表,后续没法拿到这个数据去做写入操作
- 依赖外部变量
t1容易出错,万一输入框实际数量和t1不匹配,就会漏取或者取到不存在的元素
修正后的代码实现
1. 正确获取输入框内容的函数
function getInputValues(prefix) { var storedList = []; // 动态获取所有以prefix开头的输入框数量,不用依赖外部t1 var inputCount = document.querySelectorAll(`[id^="${prefix}"]`).length; for (var i = 0; i < inputCount; i++) { var inputElement = document.getElementById(prefix + (i + 1)); // 只把输入框的内容存入数组,空输入也做处理 if (inputElement) { storedList.push(inputElement.value.trim()); } } // 返回存储的内容列表,供后续写入使用 return storedList; }
2. 写入新页面的函数
function writeToNewPage() { var inputContents = getInputValues('uTitle'); // 打开新窗口避免覆盖当前页面 var newWindow = window.open(); // 在新窗口里构建内容 newWindow.document.write('<h1>输入内容汇总</h1>'); newWindow.document.write('<ul>'); for (var j = 0; j < inputContents.length; j++) { newWindow.document.write(`<li>${inputContents[j] || '未输入内容'}</li>`); } newWindow.document.write('</ul>'); // 结束写入,确保新窗口内容渲染完成 newWindow.document.close(); }
使用说明
- 当你需要触发写入操作时(比如绑定到一个按钮的点击事件),直接调用
writeToNewPage()就行 - 如果坚持要用原来的
t1变量,把函数里的inputCount替换成t1即可,但动态获取输入框数量的方式更靠谱,不会因为手动新增/删除输入框出现偏差
内容的提问来源于stack exchange,提问作者Jeremy
相关产品推荐
相关产品推荐

