3
    $(document).keydown(function(e){
        if (e.keyCode == 37) { 
            return false;
        }
    });

    $(".direction").click(function() {
        var direction = $(this).text();

当我单击具有 .direction 类的按钮时,将调用上面的第二个函数。当按下左键时,我想$(".direction").click(function() {用一个值调用 But(而不是 var direction = $(this).text(); 部分)这将是 var direction = value passing to function;

我怎样才能做到这一点?

4

4 回答 4

4

添加两个方法都使用的另一个函数:

$(document).keydown(function(e){
     if (e.keyCode == 37) { 
          move("left");
     }
});

$(".direction").click(function() {
     move($(this).text());
});

function move(newDirection)
{
     var direction = newDirection;
}
于 2012-06-13T12:47:59.313 回答
2

我会使用另一个函数来执行此操作,而不是尝试触发点击处理程序。

$(document).keydown(function(e){
    if (e.keyCode == 37) { 
        updateDirection("Something else");
    }
});

$(".direction").click(function() {
    updateDirection($(this).text());
});

function updateDirection(d) {
    var direction = d
}
于 2012-06-13T12:48:43.090 回答
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());
});​

在此处查看实时示例

于 2012-06-13T12:48:50.877 回答
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);
});
于 2012-06-13T12:56:18.310 回答