Is there a way to do two different functions?
For an example, if I want the user to do both click and keypress that wi开发者_JS百科ll give the same output. I would not like to have two of the same codes.
If I had something like
$('#next').click(function(){
// code goes here
});
I would like to also implement this
$(document).keydown(function(e){
if (e.keyCode == 37) {
alert( "left pressed" );
return false;
}
});
that will be part of the click. Any suggests? Thank you!!
function myFunc() {
alert("left pressed");
}
$("#next").click(myFunc);
$(document).keypress(function(e) {
if(e.keyCode == 37) myFunc();
});
You could also have myFunc() handle both events like so..
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);
Wrap the common code in a separate function and call from within your selector functions? Or am I misunderstanding your question?
So:
function doSomeStuff() {
// common code here
}
$('#next').click(function() {
doSomeStuff();
});
$(document).keydown(function(e) {
if(e.keyCode == 37) {
alert("left pressed") ;
doSomeStuff();
return false;
}
});
something like this
function clicky(e) {
e.preventDefault();
console.log('do stuff');
}
$('#next').click(clicky);
$(document).keydown(clicky);
you want to write the function and call it later
live example: http://jsfiddle.net/mPhAZ/
$(document).keydown(function(e){
if (e.keyCode == 37) {
$('#next').click();
}
});
.click() is a standard javascript function that can be used to simulate clicking a button.
精彩评论