2012-08-22 47 views
2

我有我正在使用的以下代碼行。但它只是似乎redunent,我很好奇,如果有一個優化的替代以下...如何用jquery壓縮代碼行?

if(mkey[65]){ //this is left! (a) 
    var nextpos = $("#item").x()-player.speed; 
    if(nextpos > 0){ 
     $("#item").x(nextpos); 
    } 
} 
if(mkey[68]){ //this is right! (d) 
    var nextpos = $("#item").x()+player.speed; 
    if(nextpos < pg.width - 100){ 
     $("#item").x(nextpos); 
    } 
} 
if(mkey[87]){ //this is up! (w) 
    var nextpos = $("#item").y()-player.speed; 
    if(nextpos > 0){ 
     $("#item").y(nextpos); 
    } 
} 
if(mkey[83]){ //this is down! (s) 
    var nextpos = $("#item").y()+player.speed; 
    if(nextpos < pg.height - 30){ 
     $("#item").y(nextpos); 
    } 
} 

我想過使用jQuery的每一種方法,但只花了我到目前爲止,因爲我不知道您是否可以將自定義JavaScript函數存儲到數據對象中...

感謝您的任何建議!

這是我曾嘗試......(沒有運氣)

$.each([ 
    {keypress: mkey[65], item:$("#item").x()-player.speed}, 
    {keypress: mkey[68], item:$("#item").x()+player.speed}, 
    {keypress: mkey[87], item:$("#item").y()-player.speed}, 
    {keypress: mkey[83], item:$("#item").y()+player.speed} 
], function(i, obj) { 

    if (obj.keypress) { 
    if(obj.item > 0) { $("#item").x(obj.item);} 
    } 

}); 
+0

* [你有什麼試過?](http://mattgemmell.com/2008/12/08/what-have-you-tried/)* – zzzzBov

+0

http://codereview.stackexchange.com/ – MetalFrog

回答

1

使用switch語句的鍵碼。

也有它,但我不是它的粉絲: http://api.jquery.com/event.which/

switch語句

switch($keycode){ 

case 43: 
// Your code or function_name(); 
break; 

case 99: 
// Your code or function_name(); 
break; 
} 
+0

怎麼會你爲多個功能設置了一個開關盒? – blackhawk

+0

添加到主要答案。 – Darcey

2

在JavaScript中,函數是一個對象,所以這不是一個問題。問題在於是否通過使用一行代碼來保存任何代碼行,並且即使是這樣,也不管它是否可維護。這裏是一個可能的解決方案:

$.each([ 
    { which: 65, fn: $('#item').x, plus: -player.speed, comparison: 'gt', what: 0 }, 
    { which: 68, fn: $('#item').x, plus: player.speed, comparison: 'lt', what: pg.width - 30), 
    { which: 87, fn: $('#item').y, plus: -player.speed, comparison: 'gt', what: 0 }, 
    { which: 83, fn: $('#item').y, plus: player.speed, comparison: 'lt', what: pg.height - 30) 
], function() { 
    var o = this, 
     w = mkey[o.which], 
     nextpos = o.fn() + o.plus; 
    if ((o.comparison === 'gt' && nextpos > o.what) || 
     (o.comparison === 'lt' && nextpos < o.what)) { 
     o.fn(nextpos); 
    } 
}); 

我沒有測試過這種或任何(提供jsFiddlejsBin與您的代碼,我可以),但希望你能看到我用它去。再次,不確定這是否有幫助,因爲這個代碼比原始代碼更不可讀。通過縮小,原始代碼的運行速度將快於此代碼。祝你好運。

+0

謝謝,我真的很感激你抽出時間來幫助我。仍在調查...... – blackhawk