开发者

jQuery Trigger to click

I开发者_如何学运维'm using jquery hotkeys to bind and run a function when the user taps their right arrow key. When jquery hotkeys detects the right arrow being hit on the keyboard, I want jQuery to click the next pagination link. For some reason this isn't working. I've confirmed pagination works. Also confirmed the selector looks good by getting the below to work with instead of a .trigger, a .remove().

$(document).ready(function() { 

 jQuery(document).bind('keydown', 'right',function (evt){
  $('#header').find('.next_page').trigger('click');
 });

});

<div id="view-header">
 <a class="next_page" href="/books/?page=2" rel="next">Next →</a>
</div>

Any thoughts on this one? Thanks


why not just do a .click()?

alternately you could pick up the href and use javascript to take the user there.

location.href = ''+$('#header').find('.next_page').attr('href')+'';


Could just be that you are using #header in the jQuery where you are using view-header as the ID in the html. I'm doubting it's as simple as that. It's difficult to call a native click event such as the one you describe. What happens with .trigger('click') is it calls the onClick event (and there is none). Perhaps the best thing to do is to create a click handler:

 $('.next_page').click(function(){
location.href = $(this).attr('href');
});

This is a click handler: now when you call .trigger('click') it should run this code. I think this could be made much simpler, from what you have displayed (i.e. you could just change the location.href value in the keydown handler and avoid forcing a click), but perhaps you have other plans. :)

UPDATE:

This code works perfectly. It might not be as compact as it could be, but I tried to maintain as much from your original post as I could. Enjoy.

<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(function(){
$('.next_page').click(function(){
location.href = $(this).attr('href');
});
});
$(document).keydown(function(event) {
 if(event.keyCode==39) {
                    $('.next_page').trigger('click')
                }
            });
</script>
<div id="header">
 <a class="next_page" href="/books/?page=2" rel="next">Next →</a>
</div>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜