Binding Keyboard to Onclick Event

与世无争的帅哥 提交于 2019-12-25 00:27:25

问题


I am having problems with a jquery slideshow where I want to bind next/right to make the images jump forwards/back.

I used the following code to attempt to do it but it simply refreshes the page.

<script>
$(function() {$(document).keyup(function(e) {
switch(e.keyCode) { case 37 : window.location = $('#prev a').attr('href'); break;
case 39 : window.location = $('#next a').attr('href'); break; }});});
</script>   

The I was attempting to call were:

<a href='#' id='prev' onclick='show_image($prev); return false;'>

and

<a href='#' id='next' onclick='show_image($next); return false;'>

Does anyone know an easy way to cut out the middle man and simply bind left/right to the onclick event for each?

Anyhelp would be much appreciated!


回答1:


This should work:

$(function() {
    $(document).keyup(function(e) {
        switch (e.keyCode) {
        case 37:
            $('#prev a')[0].onclick();
            break;
        case 39:
            $('#next a')[0].onclick();
            break;
        }
    });
});​

Just call the onclick event handler of the left or right button based on which key you pressed.




回答2:


$(function() {
    $(document).keyup(function(e) {
        switch (e.keyCode) {
        case 37:
            $('#prev').click();
            break;
        case 39:
            $('#next').click();
            break;
        }
    });
});​


来源:https://stackoverflow.com/questions/10541606/binding-keyboard-to-onclick-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!