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

如何实现单搜索框基于输入数据类型跳转员工ID/姓名查询?

单搜索框自动识别类型实现员工查询改造方案

改造步骤与核心逻辑

  1. 移除原有两个独立的搜索表单,合并为单一的搜索输入框和搜索按钮
  2. 通过正则判断输入内容:若为纯数字则匹配Employee ID查询接口,否则匹配Employee Name查询接口
  3. 根据判断结果动态生成对应的查询URL,打开新窗口展示结果

改造后的完整代码

<html>
    <head>
        <style>
            body {
                background-color: yellow;
                text-align: center;
                font-family: 'Amatic SC', cursive;
                font-size: 24px;
                margin-left: 150px;
                margin-right: 150px;
            }
            h1 {
                font-size: 60px;
            }
            p {
                font-size: 20px;
            }
        </style>
    </head>
    <body>
        <h1>Welcome to Employee Database!</h1>
        <p>View <a href="http://localhost:8080/tyrrest/employees">Employee List</a>.</p>
        <p style="font-size: 20px;">Search Employee by ID or Name</p>
        <form>
            <input id="employee-search-input" type="text" placeholder="Enter ID or Name">
            <input class="thmas-button" type="button" value="Search">
        </form>
        <p style="font-size:12px;"><br><br><br><br><br><br><a href="http://localhost:8080/tyrrest/employees?fields=name">Employee Name List</a></p>
        <p style="font-size:12px;"><a href="http://localhost:8080/tyrrest/employees?fields=id">Employee Id List</a></p>
        <script type="text/javascript">
            const searchButton = document.querySelector('.thmas-button');
            searchButton.addEventListener('click', () => {
                const inputValue = document.querySelector('#employee-search-input').value.trim();
                if (!inputValue) {
                    alert('Please enter a search value');
                    return;
                }
                // 判断输入是否为纯数字(Employee ID)
                const isId = /^\d+$/.test(inputValue);
                const searchParam = isId ? 'id' : 'name';
                const URL = `http://localhost:8080/tyrrest/employees?${searchParam}=${inputValue}`;
                window.open(URL, '_blank');
            });
        </script>
    </body>
</html>

关键代码说明

  • 输入框简化:将原有的两个输入框合并为id="employee-search-input"的单一输入框,添加占位提示用户可输入ID或名称
  • 类型判断逻辑:使用正则表达式/^\d+$/.test(inputValue)检测输入是否为纯数字,以此区分ID和名称类型
  • URL动态生成:根据判断结果选择对应的查询参数(id或name),拼接成目标URL后打开新窗口
  • 空值校验:添加输入为空时的提示,避免无效请求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 09:33:29