You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

搜索框输入div ID控制元素显隐失效问题排查(附代码)

问题诊断与修复方案

我一眼就发现了问题所在——你在获取搜索框输入值的时候,错误地使用了+运算符把字符串转换成了数字类型!

核心问题分析

看这段代码:

var string = +document.getElementById("search").value;

当用户输入cnn时,+"cnn"会被强制转换为NaN(非数字),此时NaN == "cnn"的结果永远是false,所以你的隐藏逻辑根本不会触发,只会一直执行else里的显示代码。

修复后的完整代码

HTML(无需修改,保持原样)

<body> 
  <h1 class="title">News Journal</h1> 
  <h6 class="motto">What's better than having multiple sources ?</h6> 
  <input type="text" class="search" placeholder="Search for a website..." id="search"> 
  <div id="news-container"> 
    <p class="mostViewed">Most visited news websites...</p> 
    <div class="container"> 
      <div class="divCNN" id="cnn"> 
        <a target="_blank" href="https://www.cnn.com/"><img src="https://pmcdeadline2.files.wordpress.com/2016/11/cnn-logo-2.jpg?w=892&h=598&crop=1" class="CNN"></a> 
        <p class="description">CNN was founded in 1980 by American media proprietor Ted Turner as a 24-hour cable news channel. It was the first all-news television channel in the United States and CNN website has an average of 112 millions unique monthly visitors.<a target="_blank" href="https://www.cnn.com/"> Visit !</a></p> 
      </div> 
    </div> 
  </div> 
</body>

JavaScript(修正后)

function Search() {
  // 去掉多余的+号,直接获取字符串,同时用trim()去除首尾空格避免误判
  var string = document.getElementById("search").value.trim();
  // 提前获取DOM元素,避免每次触发事件都重复查询
  const cnnDiv = document.getElementById("cnn");
  
  // 用===严格相等对比,避免类型转换带来的意外问题
  if (string === "cnn") {
    cnnDiv.style.display = 'none';
  } else {
    // 输入为空或非目标值时,恢复显示
    cnnDiv.style.display = 'inline-block';
  }
}

document.addEventListener("keyup", Search);

额外优化建议

如果希望只有用户按下回车时才执行搜索逻辑(避免每次按键都触发),可以修改事件监听:

document.addEventListener("keyup", function(e) {
  if (e.key === "Enter") {
    Search();
  }
});

内容的提问来源于stack exchange,提问作者Yohan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 06:56:10