如何在哈希转换之前执行代码? [英] How do I execute code before a hashchange?
本文介绍了如何在哈希转换之前执行代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
基本上,我想构建一个 beforehashchange
事件。我想在之前执行代码 hashchange
事件影响页面(即:滚动到目标)。
我所知道的唯一能改变哈希值(并导致 hashchange
事件)的事情是:
- 点击
< a href =#foo>
,在这种情况下我可以捕获单击
事件,并检查哈希的链接。 - 手动更改URL栏中的哈希值,我可以忽略(除非有人知道某种方式)在它触发
hashchange
之前检测到这个?)
还有其他方法触发 hashchange
?
解决方案
只有 hashchange
事件。要在哈希更改之前捕获一些信息,您可以向所有链接标记添加 data-check-hash
等属性:
< pre class =lang-html prettyprint-override>
< a href =#testdata-check-hash> foo< / a>
$('body' ).on('click','a [data-check-hash]',function(e){
e.preventDefault();
var $ item = $(e.currentTarget),
hashValue = $ item.attr('href')。slice(1);
//这里是哈希值更改前的检查代码
window.location.hash = hashValue;
返回false;
});
Basically, I want to construct a beforehashchange
event. I want to execute code before the hashchange
event affects the page (i.e.: scrolls to the target).
The only things I know of that can change the hash (and cause a hashchange
event) are:
- clicking
<a href="#foo">
, in which case I could capture theclick
event, and check for a link to a hash. - changing the hash in the URL bar manually, which I can probably ignore (unless someone knows a way to detect this before it triggers the
hashchange
?)
Are there other ways to trigger a hashchange
?
解决方案
There is only hashchange
event. To capture some information before hash change, you can add a attribute like data-check-hash
to all link tags:
<a href="#test" data-check-hash>foo</a>
$('body').on('click', 'a[data-check-hash]', function(e) {
e.preventDefault();
var $item = $(e.currentTarget),
hashValue = $item.attr('href').slice(1);
// here goes your check code before hash change
window.location.hash = hashValue;
return false;
});
这篇关于如何在哈希转换之前执行代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文