当前位置: 动力学知识库 > 问答 > 编程问答 >

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>
分享给朋友:
您可能感兴趣的文章:
随机阅读: