[英]Why does my keypress handler not work when I use anchors
I use jQuery for my homepage and add a keylistener when the window is loaded. 我在主页上使用jQuery,并在加载窗口时添加了侦听器。 It looks like this: 看起来像这样:
$(window).load(function(){
var debug = $('#debug'); // this is a fixed div I use to print debug
// information to the screen
$(window).keypress(function(event) {
var keyCode = event.keyCode ? event.keyCode : event.which;
debug.text(keyCode);
if (keyCode == 106 || keyCode == 40)
nextCard();
else if (keyCode == 38 || keyCode == 107)
prevCard();
});
});
You can jump from one card to another using the arrow up and arrow down key or 'j' and 'k'. 您可以使用上箭头和下箭头键或“ j”和“ k”从一张卡跳转到另一张卡。 It works fine as long the page is loaded without jumping to an anchor. 只要加载页面而不跳转到锚点,它就可以正常工作。 That means when I go to the page like http://www.blah.com it works fine but when I load it like this http://www.blah.com#anchor it doesn't work anymore. 这意味着当我转到http://www.blah.com之类的页面时,它可以正常工作,但是当我以http://www.blah.com#anchor这样的方式加载它时,它不再起作用。
Update: $(window).load() gets fired, so this is not the problem. 更新: $(window).load()被触发,所以这不是问题。
Do you have any ideas what the problem could be? 您有什么想法可能是问题吗? Thanks! 谢谢!
If you cant find an easy solution, you could try to rebind your function everytime when the hash changes. 如果找不到简单的解决方案,则可以在每次哈希更改时尝试重新绑定函数。 For example with this plugin http://benalman.com/projects/jquery-hashchange-plugin/ 例如,使用此插件http://benalman.com/projects/jquery-hashchange-plugin/
I found the problem. 我发现了问题。 It actually had nothing to do with the keypress handler. 实际上,它与按键处理程序无关。 It was a handler that initiates a scrolling animation whenever someone enters the page with a hash in the URL. 它是一个处理程序,只要有人进入URL中带有哈希值的页面,它就会启动滚动动画。
Nevertheless thanks for making me think about my code :P next time I try to consider such bugs before I post here.... 尽管如此,还是感谢您让我考虑一下我的代码:P下次我尝试在发布之前在这里考虑这些错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.