【问题标题】:Get hash from url and click link with data-attribute on page load从 url 获取哈希并在页面加载时单击带有数据属性的链接
【发布时间】:2020-12-04 23:40:06
【问题描述】:

我的问题是这个。假设我的页面有 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 部分......所以字符串没用......

我该如何解决这个问题?非常感谢。

【问题讨论】:

    标签: jquery hash attributes


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2011-07-31
      • 2015-05-05
      • 2017-11-18
      • 2012-06-23
      • 1970-01-01
      • 2015-11-08
      • 2011-04-26
      • 1970-01-01
      • 2011-12-26
      相关资源
      最近更新 更多