如何使用数组和对象加速这个慢动作jquery脚本
how to speed up this slow-motion jquery script with array and objects?
在我的网站上,我有一组大小不同的输入按钮。
// 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
相关文章:
- jquery fancybox+angularJS:fancybox按钮动作问题
- jQuery:从上到下切换('慢速')动画
- Jquery.hide()和.show()在firefox上运行速度较慢,但在chrome上运行良好
- HTML画布慢动作
- 我的jQuery运行有点慢.我该如何加快速度
- jquery选择器在1000+元素与450Mhz机器时变慢
- JQuery 数据表列数据更新工作太慢
- 在附加元素时使用jQuery比使用JavaScript慢得多
- 切换到全屏时 Javascript/jQuery 速度变慢
- 动作脚本3中的链接按钮 + jQuery 集成中的淡出
- jQuery 对 scrollTop() 的响应速度很慢
- 当您使用 Jquery 按下按钮时,我正在尝试使我的页面滚动速度变慢
- 调试慢 jQuery 代码
- 慢速jQuery动画-更改宽度
- 如何使用数组和对象加速这个慢动作jquery脚本
- 在慢速jQuery中设置功能显示/隐藏按钮
- 谷歌地图API更新后的复选框动作jQuery
- 检测鼠标滚动动作jQuery
- jQuery的慢动作
- 使用 JavaScript 以慢动作替换 HTML