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

jQuery文本关联功能仅生效两次问题排查

问题分析与解决方案

问题根源

  1. 重复绑定点击事件:同一个按钮绑定了两个click回调,逻辑冗余且易引发执行顺序问题。
  2. 未重置显示状态:当某个div被设置为display:block后,后续点击切换城市时,之前的div不会自动隐藏,两个div位置重叠,视觉上无变化,导致误以为脚本失效。

修正后的代码

JavaScript 部分

$("#b").click(function() {
  // 每次点击先隐藏所有目标div,重置状态
  $(".tim1, .tim2").css("display", "none");
  
  var inputVal = $("#pass").val().trim();
  if (inputVal === "toronto") {
    $(".tim1").css("display", "block");
  } else if (inputVal === "ottawa") {
    $(".tim2").css("display", "block");
  }
});

完整可运行代码

<!DOCTYPE html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <style>
    body {
      background-color: #6A6A6A;
    }

    .tim1 {
      background-color: #000000;
      position: absolute;
      top: 40px;
      left: 10px;
      width: 100px;
      height: 100px;
      display: none;
    }

    .tim2 {
      background-color: #525119;
      position: absolute;
      top: 40px;
      left: 10px;
      width: 100px;
      height: 100px;
      display: none;
    }
  </style>
</head>
<body>
  <input type="text" id="pass"> <input type="button" id="b" value="Guess">
  <div class="tim1"></div>
  <div class="tim2"></div>

  <script>
    $("#b").click(function() {
      $(".tim1, .tim2").css("display", "none");
      var inputVal = $("#pass").val().trim();
      if (inputVal === "toronto") {
        $(".tim1").css("display", "block");
      } else if (inputVal === "ottawa") {
        $(".tim2").css("display", "block");
      }
    });
  </script>
</body>
</html>

改进说明

  • 合并按钮点击事件,逻辑更集中,避免重复绑定。
  • 每次点击先重置所有目标div的显示状态,确保切换城市时能看到正确的元素。
  • 添加trim()处理输入值,避免用户输入空格导致匹配失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 14:25:00