jquery - 从 url 获取哈希并在页面加载时单击带有数据属性的链接
问题描述
我的问题是这个。假设我的页面有网址www.mysite.com/test。在这个测试页面中有一个 data-id="vmax" 的链接。
<a href="some-url-here-doesn't-matter" data-id="vmax">Link</a>
因此,如果我访问带有哈希 #vmax 的 url,例如 www.mysite.com/test/#vmax,我需要获取 #vmax 部分,删除 # 并单击带有 data-id="vmax" 的链接
我到目前为止尝试的是:
jQuery(window).load(function() {
var targetHash=jQuery(window.location.hash.slice(1));
console.log(targetHash);
jQuery('a[data-slug="'+targetHash+'"]').click();})
控制台日志告诉我哈希中的 # 已成功删除,但单击事件从未发生。实际上,console.log 在调试器中给出了这一行:n.fn.init [prevObject: n.fn.init(1), context: document, selector: "vmax"]
如果我将代码更改为
jQuery(window).load(function() {
var targetHash=jQuery(window.location.hash.slice(1));
console.log(targetHash);
jQuery('a[data-slug="vmax"]').click();})
点击事件成功发生。作为一个可能很愚蠢的想法,我尝试使用 String() 函数将变量 targetHash 转换为字符串,但 console.log 完全丢失了 vmax 部分......所以字符串没用......
我怎么解决这个问题?提前谢谢了。
解决方案
我找到了答案...而不是var targetHash=jQuery(window.location.hash.slice(1));
将变量更改为var targetHash=window.location.hash.slice(1);
不应该将其包装在 jquery 中...:/。
推荐阅读
- javascript - vuex 提交时超出了最大 calstack 大小
- excel - 在保存之前询问文件名
- javascript - 比较两个数组后仅删除第一个重复值和所有其他匹配值
- perl - 无法在 Perl 中安装 GD 模块
- git - 做完 git push heroku master 我们应该做 git push origin master
- xaml - Xamarin Forms 使用反射获取可绑定属性的属性
- python - 加载在线托管的 TensorFlow (.h5) 模型
- c# - if-else 条件不能按预期工作
- prometheus - 使用 Traefik Prometheus 计算 API 的平均响应时间
- python - 如何获得用户输入和随机生成的数字的总和?