2012-06-13 41 views
3
$(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 = value傳遞給函數;來自另一個jQuery的呼叫功能

我該怎麼做?

+0

如果我如何歸還的關鍵目標事件回答代碼是不正確的,(返回該元素的文本),請澄清你想要的行動。 –

回答

4

添加所使用的兩種方法的另一個功能:

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

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

function move(newDirection) 
{ 
    var direction = newDirection; 
} 
2

我會用另一種功能,要做到這一點,而不是試圖觸發單擊處理程序。

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

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

function updateDirection(d) { 
    var direction = d 
} 
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

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); 
});