从 url 获取哈希并在页面加载时单击带有数据属性的 link
Get hash from url and click link with data-attribute on page load
我的问题是这样的。假设我的页面有 url www.mysite.com/test 。在这个测试页面中有一个 link with data-id="vmax".
<a href="some-url-here-doesn't-matter" data-id="vmax">Link</a>
因此,如果我访问带有散列#vmax 的url,例如www.mysite.com/test/#vmax,我需要获取#vmax 部分,删除# 并单击带有数据的link -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... :/.
我的问题是这样的。假设我的页面有 url www.mysite.com/test 。在这个测试页面中有一个 link with data-id="vmax".
<a href="some-url-here-doesn't-matter" data-id="vmax">Link</a>
因此,如果我访问带有散列#vmax 的url,例如www.mysite.com/test/#vmax,我需要获取#vmax 部分,删除# 并单击带有数据的link -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... :/.