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

index.ts中点击搜索按钮后URL无法携带inputValue查询参数求助

问题:TypeScript中点击搜索按钮后URL查询参数为空

我们在index.ts中使用以下代码时,点击searchbutton按钮后,URL无法携带inputValue作为查询参数。点击后URL显示为https://login.amaf.ae/SitePages/AMAF-Search.aspx?search=,经控制台检查search参数为空。此前用HTML和script标签实现该功能可正常运行,但使用TS时出现此问题。

$(document).ready(function() {
  $(".searchbutton").on("click", function() {
    let inputValue = $(".searchinput").val();
    console.log("SearchValue: " + inputValue);
    window.location.href = siteUrl + "/SitePages/AMAF-Search.aspx?search=" + encodeURIComponent(inputValue);
  });
});

解决方法

  • 校验jQuery选择器匹配结果
    在浏览器控制台执行$(".searchinput"),确认返回的DOM元素是目标输入框,避免因类名重复或选择器错误获取到空元素。

  • 确认siteUrl变量的有效性
    检查siteUrl是否在当前作用域正确声明并赋值,TypeScript中未定义的变量会被编译报错,若为全局变量需添加declare var siteUrl: string;声明。

  • 处理.val()的类型不确定问题
    TypeScript中$(".searchinput").val()返回类型为string | number | string[] | null,直接传入encodeURIComponent可能引发异常,可添加类型断言和空值兜底:

    let inputValue = $(".searchinput").val() as string || "";
    
  • 阻止按钮默认提交行为
    若按钮属于表单内的提交按钮,点击时会触发表单默认跳转,导致参数未完成拼接。需在事件回调中添加阻止默认行为的代码:

    $(".searchbutton").on("click", function(e) {
      e.preventDefault();
      let inputValue = $(".searchinput").val() as string || "";
      console.log("SearchValue: " + inputValue);
      window.location.href = siteUrl + "/SitePages/AMAF-Search.aspx?search=" + encodeURIComponent(inputValue);
    });
    
  • 检查TS编译后的JS代码
    查看TypeScript编译生成的JavaScript文件,确认变量逻辑未被编译错误修改,比如变量重命名、作用域丢失等问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 12:17:52