如何在JS中关联输入框、按钮与函数实现输入字符串处理
问题排查
- 你已正确通过
document.getElementById("myText").value拿到了输入框内容存入变量x,但后续所有逻辑都在调用全局预设的固定字符串str,完全没用到用户输入的内容 - 代码存在语法错误:
myFunction末尾多了一个多余的闭合花括号,还调用了不存在的gridStr函数 - 原生
document.write方法会直接清空整个原有页面再写入内容,体验很差,建议直接输出到页面已有的demo元素中
修复后完整可运行代码
<input type="text" id="myText" value="String"> <p>点击"Try it"按钮执行转换</p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script> function myFunction() { // 读取用户输入的字符串 const inputStr = document.getElementById("myText").value; const strLength = inputStr.length; let index = 0, row, column; row = Math.floor(Math.sqrt(strLength)); column = Math.ceil(Math.sqrt(strLength)); if (row * column < strLength) { row = column; } // 初始化网格数组 const grid = new Array(row); for (let i = 0; i < row; i++) { grid[i] = new Array(column).fill(0); } // 将字符串填充到网格中 for (let i = 0; i < row; i++) { for (let j = 0; j < column; j++) { if(index < strLength) { grid[i][j] = inputStr[index]; } index++; } } // 拼接输出结果 let resultHtml = ''; for (let i = 0; i < row; i++) { for (let j = 0; j < column; j++) { if (grid[i][j] === 0) break; resultHtml += grid[i][j]; } resultHtml += "<br>"; } // 写入到页面展示区 document.getElementById("demo").innerHTML = resultHtml; } </script>
修改说明
- 所有字符串处理逻辑统一使用从输入框读取的
inputStr变量,移除了全局固定字符串和无效函数调用 - 修正了语法错误,优化了变量命名可读性
- 调整输出逻辑,结果直接展示在输入框下方,不会覆盖原有页面内容
内容的提问来源于stack exchange,提问作者Nemanja Ilic
相关产品推荐
相关产品推荐

