如何使用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-each方法,但只花了这么长时间,因为我不知道是否可以将自定义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);}
  }
});

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

我还没有测试过这个或任何东西(在你的代码中提供一个jsFiddle或jsBin,我可以),但希望你能看到我的想法。同样,我不确定这是否真的有帮助,因为这段代码的可读性比原来的要差得多。通过缩小,原始代码将比此代码运行得更快。祝你好运

在键代码上使用switch语句。

还有什么,但我不喜欢:http://api.jquery.com/event.which/

切换语句

switch($keycode){
case 43:
// Your code or function_name();
break;
case 99:
// Your code or function_name();
break;
}

最新更新