首页 > 解决方案 > 从 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 部分......所以字符串没用......

我怎么解决这个问题?提前谢谢了。

标签: jqueryhashattributes

解决方案


我找到了答案...而不是var targetHash=jQuery(window.location.hash.slice(1));将变量更改为var targetHash=window.location.hash.slice(1); 不应该将其包装在 jquery 中...:/。


推荐阅读