如何在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
相关产品推荐
相关产品推荐

