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

如何在JavaScript和HTML中检测文本框是否为空并执行对应函数

实现输入框状态的定时检测与标题控制

你只需要在setInterval的回调函数中添加输入框状态判断逻辑即可,具体修改如下:

<html>

<head>
  <title>
    please choose title
  </title>
</head>

<body>
    <input type="text" id="title" size="150" oninput="changePageTitle()">
  <br>
  <button onclick="changePageTitle()">
    *click me if page title doesn't change
  </button>

  <script type="text/javascript">
    function changePageTitle() {
      const newPageTitle = document.getElementById('title').value;
      document.title = newPageTitle;
    }
const interval = setInterval(function(){
  // 获取输入框元素
  const titleInput = document.getElementById('title');
  // 判断输入框是否为空(去除首尾空白后)
  if (!titleInput.value.trim()) {
    // 为空时执行changePageTitle
    changePageTitle();
  } else {
    // 不为空时重置标题为指定文本
    const newPageTitle = "please choose title";
    document.title = newPageTitle;
  }
}, 1000);
  </script>
</body>

</html>

关键细节说明:

  • 用trim()处理输入框内容,避免用户输入的空格被误判为有效内容
  • 在changePageTitle函数中添加const声明变量,防止全局变量污染
  • 定时逻辑每1秒执行一次,自动根据输入框状态调整页面标题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 04:53:16