![](/img/trans.png)
[英]Hashchange jQuery plugin - obtaining the current hash when clicking an anchor
[英]$(window).on('hashchange') Not firing when I change the hash with Jquery programmatically?
我有两个Jquery函数之一是
$('.navbar-nav').on('click', 'a', function (event) {
event.preventDefault(); //prevents quick jumps.
var href = $.attr(this, 'href');
href = href.replace(/^\//, '');
if (href != '#') {
if ($(href).length) {
var g = $(href).offset().top - h;
$bod.animate({
scrollTop: g - 5
}, 1000,
function () { //change hash here
if (history.pushState) {
history.pushState(null, null, href);
}
else {
window.location.hash = href;
}
});
}
};
var g = $(window).width();
if (g <= 768) {
$(".navbar-toggle").click();
}
});
第二个功能是
$(window).on('hashchange', function() {
alert(location.hash);
});
哈希更改事件不会发出警报。 我猜我可能没有正确使用event.preventdefault()
。 我是Jquery的新手,无法理解为什么未触发hashchange
。 有任何想法吗?
编辑:这段代码包装在$(document).ready()
和var $bod = $('html,body');
这可能是原因吗? 编辑:控制台不显示任何Jquery错误。
据我所知,“ hashchange”不是本地的jQuery事件。 jQuery对我也不起作用。 但是,仅使用常规JS即可正常工作,即:
window.addEventListener('hashchange', function() {
// DO STUFF
}, false);
和window.attachEvent ...用于较旧版本的IE
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.