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

如何使用JavaScript函数修改href属性实现页面跳转?

问题:按钮点击跳转链接失效的解决办法

原代码核心问题梳理

你当前的代码存在几个关键问题导致跳转失效:

  • <button>标签本身没有href属性,修改它的href完全不会触发页面跳转
  • HTML标签嵌套错误:<input>是自闭合标签,不能包裹<button>
  • JS里result变量未定义,没有获取输入框的实际内容
  • 模板字符串误用双引号,只有反引号才能解析${}变量
  • 变量名错误:availableKey[i]应为availableKeywords[i]
  • HTML中button的onClick="submitClicked"和实际函数名submitBtn不匹配

修正后的代码实现

1. 调整HTML结构

<input
  type="text"
  placeholder="Search"
  id="input-box"
  autocomplete="off"
  style="width: 250px;">
<button id="submitbtn">提交</button>

2. 修复JS跳转逻辑

// 假设你已定义关键词数组
const availableKeywords = ["前端", "后端", "全栈"];

document.getElementById("submitbtn").onclick = submitBtn;

function submitBtn() {
  // 获取输入框的内容并去除首尾空格
  const inputVal = document.getElementById("input-box").value.trim();
  // 遍历匹配关键词
  for(let i=0; i<availableKeywords.length; i++){
    if (inputVal === availableKeywords[i]){
      // 直接通过window.location.href实现跳转
      window.location.href = `/index2.html?key=${availableKeywords[i]}`;
      // 匹配到后跳出循环,避免多余遍历
      break;
    }
  }
}

额外优化方案

可以用find方法替代for循环,让代码更简洁:

function submitBtn() {
  const inputVal = document.getElementById("input-box").value.trim();
  const matchedKey = availableKeywords.find(key => key === inputVal);
  if (matchedKey) {
    window.location.href = `/index2.html?key=${matchedKey}`;
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 17:12:53