在我的網站上,我有一組尺寸的輸入按鈕。如何加快與數組和對象這個慢動作jquery腳本?
// 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的移動網站上使用它,所以我知道我得到了300ms的延遲點擊。
不過劇本非常緩慢exectute,所以我不知道,如果有人可以點我到任何「性能增強」爲以下幾點:
// 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);
});
涼爽。試試這個。 – frequent 2012-03-24 11:15:34