例如,如果我希望用户同时执行单击和按键,则会提供相同的输出。我不想有两个相同的代码。
如果我有类似
的话$('#next').click(function(){
// code goes here
});
我也想实现这个
$(document).keydown(function(e){
if (e.keyCode == 37) {
alert( "left pressed" );
return false;
}
});
这将是点击的一部分。有什么建议?谢谢!!
答案 0 :(得分:5)
function myFunc() {
alert("left pressed");
}
$("#next").click(myFunc);
$(document).keypress(function(e) {
if(e.keyCode == 37) myFunc();
});
你也可以让myFunc()处理这两个事件..
function myFunc(e) {
// First we check to see if this event has a keyCode property
// If so, then we need to check the value of that keyCode.
// If it doesn't match the value we're trying to capture,
// then we just "exit" the function by returning false.
if(e.keyCode && e.keyCode != 37) {
return false;
}
alert("left pressed");
}
// Since myFunc() handles both scenarios, we can
// bind it to both objects.
$("#next").click(myFunc);
$(document).keypress(myFunc);
答案 1 :(得分:1)
类似这样的事情
function clicky(e) {
e.preventDefault();
console.log('do stuff');
}
$('#next').click(clicky);
$(document).keydown(clicky);
你想写这个函数并稍后调用它
答案 2 :(得分:1)
将公共代码包装在单独的函数中并从选择器函数中调用?或者我误解了你的问题?
所以:
function doSomeStuff() {
// common code here
}
$('#next').click(function() {
doSomeStuff();
});
$(document).keydown(function(e) {
if(e.keyCode == 37) {
alert("left pressed") ;
doSomeStuff();
return false;
}
});
答案 3 :(得分:0)
$(document).keydown(function(e){
if (e.keyCode == 37) {
$('#next').click();
}
});
.click()是一个标准的javascript函数,可用于模拟单击按钮。