如何使用数组和对象加速这个慢动作jquery脚本

how to speed up this slow-motion jquery script with array and objects?

本文关键字:慢动作 jquery 脚本 加速 何使用 数组 对象      更新时间:2023-09-26

在我的网站上,我有一组大小不同的输入按钮。

// input elements
<input type="button" value="S" class="pblI" />
<input type="button" value="M" class="pblI" />
<input type="button" value="L" class="pblI" />
// output element
<input type="text" id="sizeMaster" value="" />

用户可以点击这些按钮来构建分类,例如尺寸S/1、M/2、L/3。点击尺寸S可将S/1添加到产品组合中。接下来点击S使其S/2,依此类推

我在Jquery mobile的移动网站上使用它,所以我知道我会得到300毫秒的延迟点击。

尽管如此,脚本执行起来还是非常慢,所以我想知道是否有人能为我指出以下方面的"性能增强":

// an array and defaults
var remSize = [],
remIndex = -1,
szString, remData, i;
// click listener
$(document).on('click', '.pblI', function () {
    // when clicked, construct a new object ala {size=S;qty=1}
    szString = "";
    remData = {};
       remData.size = $(this).find('input').val();
       remData.qty = 1;
    // loop through the array to see whether the size is already in there
    for (i = 0; i < remSize.length; i++) {
        // return index position of size (otherwise index stays on -1)
        if (remSize[i].size == remData.size) {
            remIndex = i;
            break;
        }
    }
  // if the size is not in the array push the new object into the array
  if (remIndex == -1 || typeof remIndex == "undefined") {        
    remSize.push(remData);
    } else {
       // else increase qty of exisiting size by 1          
       ++remSize[remIndex].qty;
       }
// create input string to display for the user
$(remSize).each(function (i) {
    szString = szString + remSize[i].size + "/" + remSize[i].qty + " ";
    // this will output something like this: 34/1 36/2 38/1
    });
// update input field
$('#sizeMaster').val(szString);
});

我不知道什么是慢的,但你可以更快地完成这些部分:

    for (i = 0; i < remSize.length; i++) {
        // return index position of size (otherwise index stays on -1)
        if (remSize[i].size == remData.size) {
            remIndex = i;
            break;
        }
    }

    for (i=0,j=remSize.length;i<j;++i) {
        // return index position of size (otherwise index stays on -1)
        if(remSize[i].size === remData.size) {
            remIndex = i; i = j;
        }
    }

$(remSize).each(function (i) {
    szString = szString + remSize[i].size + "/" + remSize[i].qty + " ";
    // this will output something like this: 34/1 36/2 38/1
    });

for(i=0;i<j;++i) {
    szString += remSize[i].size + "/" + remSize[i].qty + " ";
}

$('#sizeMaster').val(szString);

document.getElementById('sizeMaster').value = szString;

但我认为这不会有什么大的不同。

编辑:当然你需要在开头定义"j"。

您可以通过监听触摸端而不是点击来消除一些延迟

下面是一个例子-http://code.google.com/mobile/articles/fast_buttons.html