如何实现输入框旁按钮点击跳转至带用户输入参数的动态域名地址
解决方案
方案1:原生JavaScript实现(推荐,完全适配你的路径格式要求)
核心用浏览器内置的window.location.origin属性自动获取当前站点的协议+域名+端口,无需硬编码配置,本地开发和线上部署自动适配。
最终代码
<!-- 给输入框加唯一id用于取值 --> <input type="text" id="targetUsername" placeholder="Enter the username to chat : " class="input-required" /> <button type="button" id="startChatBtn" class="btn btn-lg" > <i class="fas fa-paper-plane"></i> </button> <script> // 绑定按钮点击事件 document.querySelector('#startChatBtn').addEventListener('click', function () { const inputDom = document.querySelector('#targetUsername') const inputVal = inputDom.value.trim() // 非空校验,避免无效跳转 if (!inputVal) { inputDom.focus() return } // 自动拼接当前站点地址,无需手动修改localhost const jumpUrl = `${window.location.origin}/message/to=${encodeURIComponent(inputVal)}` window.location.href = jumpUrl }) </script>
关键逻辑说明
window.location.origin会自动返回当前页面的根地址,本地开发时返回https://localhost:5000,上线后自动返回你的线上域名,完全适配不同环境encodeURIComponent用于编码用户输入的特殊字符,避免地址解析错误- 保留了你原有的图标按钮样式,不需要修改原有UI逻辑
方案2:原生表单实现(如果接口支持query参数格式)
如果后端可以适配/message?to=xxx的参数格式,可以用更简洁的原生表单实现,无需写JS代码:
<form action="/message" method="GET"> <input type="text" name="to" placeholder="Enter the username to chat : " class="input-required" required /> <button type="submit" class="btn btn-lg"> <i class="fas fa-paper-plane"></i> </button> </form>
表单提交后会自动跳转到当前域名/message?to=用户输入内容,同样自动适配不同环境的域名。
内容的提问来源于stack exchange,提问作者codePerfect
相关产品推荐
相关产品推荐

