$(document).keydown(function(e){
if (e.keyCode == 37) {
return false;
}
});
$(".direction").click(function() {
var direction = $(this).text();
当我点击带有.direction类的按钮时,会调用上面的第二个函数。当按下左键时我想调用$(".direction").click(function() {
但是有一个值(而不是var direction = $(this).text(); part)它将是var direction =传递给函数的值;
我该怎么做?
答案 0 :(得分:4)
添加两种方法使用的另一个函数:
$(document).keydown(function(e){
if (e.keyCode == 37) {
move("left");
}
});
$(".direction").click(function() {
move($(this).text());
});
function move(newDirection)
{
var direction = newDirection;
}
答案 1 :(得分:2)
我会使用另一个函数来执行此操作,而不是尝试触发单击处理程序。
$(document).keydown(function(e){
if (e.keyCode == 37) {
updateDirection("Something else");
}
});
$(".direction").click(function() {
updateDirection($(this).text());
});
function updateDirection(d) {
var direction = d
}
答案 2 :(得分:1)
var changeDirection = function(data) {
var direction = data;
alert(direction);
};
$(document).keydown(function(e) {
if (e.keyCode == 37) {
changeDirection("your value here");
}
});
$(".direction").click(function() {
changeDirection($(this).text());
});
查看实时示例here
答案 3 :(得分:1)
创建一个处理事件的函数,然后调用它:
function handleMyEvent(direction){
/* do your handling here */
}
$(document).keydown(function(e){
if (e.keyCode == 37) {
var direction = e.keyCode; // or create an appropriate string for your use
// OR IF you want the value of the focused element, you can get that also:
// IF this is not what you want/mean clarify please
var direction = $(e.target).text();
handleMyEvent(direction);
return false; //still return false to prevent the default behavior
}
});
$(".direction").click(function() {
var direction = $(this).text();
handleMyEvent(direction);
});