![](/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.