You need to enable JavaScript to run this app. 如何在页面加载时自动将window.location.hash写入HTML输入框的value值
优惠活动
大模型
产品
解决方案
定价
更多

如何在页面加载时自动将window.location.hash写入HTML输入框的value值

实现方案

HTML本身无法直接解析执行window.location.hash作为属性值,必须通过JavaScript在页面加载完成后主动赋值,无需按钮触发的实现方式如下:

1. 原生JavaScript实现

HTML代码:

<input type="text" class="form-control" id="hashInput">

JS代码:

// 等待DOM结构完全加载后自动执行
document.addEventListener('DOMContentLoaded', function() {
  const inputEle = document.getElementById('hashInput');
  // 直接赋值hash,若需要去掉开头的#可改为 window.location.hash.slice(1)
  inputEle.value = window.location.hash;
});

// 可选:监听hash变化实时更新input值,无需刷新页面
window.addEventListener('hashchange', function() {
  document.getElementById('hashInput').value = window.location.hash;
});

2. jQuery实现(项目已引入jQuery时可用)

$(function() {
  // 页面加载完成后自动赋值
  $('#hashInput').val(window.location.hash);
  
  // 可选:监听hash变化实时更新
  $(window).on('hashchange', function() {
    $('#hashInput').val(window.location.hash);
  })
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 01:45:09