为什么JavaScript中input.value始终返回空字符串?
问题根因
你代码中Lisa.innerHTML +=
``的操作会触发Lisa容器的整体DOM重绘:浏览器会先清空现有容器内的所有节点,再把拼接后的HTML字符串解析为新的DOM节点插入。你之前通过createElement创建并存储的input变量,指向的是已经被移除的旧节点,自然永远读不到当前页面上输入框的内容。
修复方案
- 替换innerHTML拼接换行的逻辑,改为创建br元素后调用appendChild插入,不会破坏现有DOM节点的引用
- 输入框返回的是逗号分隔的字符串,需要先按分隔符拆分、过滤空值、转为数字数组后,再传入countPairs函数(当前你直接传字符串长度和字符串本身,参数格式不符合countPairs的要求)
修正后完整代码
document.getElementById("app").innerHTML = ` <h1 style="color:indigo">Let's Count Pairs of Socks!</h1> <h3 style="color:indigo">Enter a list of number socks:</h3> <div id=Lisa></div> `; const input = document.createElement("input"); input.setAttribute("placeholder", "22, 22, 33"); const Lisa = document.getElementById("Lisa"); Lisa.appendChild(input); const button = document.createElement("button"); button.innerText = "Get number of pairs!"; button.style.color = "indigo"; // 替换innerHTML拼接为创建br节点插入,避免重绘整个容器 Lisa.appendChild(document.createElement('br')) Lisa.appendChild(document.createElement('br')) Lisa.appendChild(button); const results = document.createElement("div"); Lisa.appendChild(results); const handleSearch = () => { const inputStr = input.value; console.log(inputStr); // 把输入的字符串转换为符合要求的数字数组 const searchList = inputStr.split(',') .map(item => Number(item.trim())) .filter(num => !isNaN(num)) const numPairs = countPairs(searchList.length, searchList); const title = document.createElement("h3"); title.innerText = "The number of pairs is....."; title.style.color = "indigo"; const pairs = document.createElement("h4"); pairs.innerText = numPairs; pairs.style.color = "indigo"; // 同样替换这里的innerHTML操作 Lisa.appendChild(document.createElement('br')) Lisa.appendChild(document.createElement('br')) Lisa.appendChild(title); Lisa.appendChild(pairs); }; button.addEventListener("click", handleSearch);
内容的提问来源于stack exchange,提问作者Lisa Modenbach
相关产品推荐
相关产品推荐

