【发布时间】: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