在点击和按键上触发相同的功能 [英] Triggering same function on both click and keypress

查看:85
本文介绍了在点击和按键上触发相同的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下功能,当单击该功能时会触发,但是如何在不创建新功能的情况下使它在回车时触发呢? (如果可能).

I have the following function which fires when clicked but how would I also make it fire on enter without creating a new function? (if possible).

$("#jump_menu select option").click(function(){
    var hash = $(this).val();
    var target_offset = $(hash).offset();
    $('html, body').animate({scrollTop:target_offset.top}, 500);
})  

推荐答案

尝试绑定到

$("#jump_menu select").change

...相反.

或者只是将其移至独立功能并绑定至所需的内容:

Alternatively just move it to a standalone function and bind to what you need:

function handler(elem) {
    var hash = $(elem).val();
    var target_offset = $(hash).offset();
    $('html, body').animate({scrollTop:target_offset.top}, 500);
}

$('#jump_menu select option').click(handler);
$('#jump_menu select').change(handler);

尽管如此,您可能需要保存并比较事件时间戳,以确保一次选择不会再次调用处理程序.

You may need to save and compare event timestamps though to ensure you don't call your handler twice for a single selection.

这篇关于在点击和按键上触发相同的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆