我的代码在我的页面中循环,当选中复选框时会导致轻微的页面延迟。有没有办法优化代码?我仍然是javascript的新手,所以我可能混合了一些东西。
var OpeningEmployees = document.getElementById('opener');
var QuantityDDOptions = jQuery('#opener option').length;
var DropDownNames = new Array();
DropDownNames[0] = "opener";
DropDownNames[1] = "mid";
DropDownNames[2] = "closer";
DropDownNames[3] = "SRTW";
DropDownNames[4] = "CR";
DropDownNames[5] = "Aisles";
DropDownNames[6] = "BD";
DropDownNames[7] = "Fridge";
DropDownNames[8] = "AP";
DropDownNames[9] = "EPV";
OpeningEmployees.onchange = function () {
var openerVals = $("#opener").val();
for (var j = 1; j < DropDownNames.length; j++){
for (var x = 0; x < QuantityDDOptions; x++) {
var EmployeelNumLine = document.getElementById(DropDownNames[j]).options[x].value;
if (openerVals == null){
jQuery("select#"+DropDownNames[j]+" option")[x].removeAttribute("disabled");
$("#"+DropDownNames[j]).multiselect("refresh");
} else if(openerVals.indexOf(EmployeelNumLine) > -1) {
jQuery("select#"+DropDownNames[j]+" option")[x]['disabled'] = "true";
$("#"+DropDownNames[j]).multiselect("refresh");
} else if(!openerVals.indexOf(EmployeelNumLine) > -1){
jQuery("select#"+DropDownNames[j]+" option")[x].removeAttribute("disabled");
$("#"+DropDownNames[j]).multiselect("refresh");
}
}
}
}
答案 0 :(得分:1)
通常,如果你的循环锁定了线程,你可以将它重构为使用超时调用的递归循环。这可以防止用户界面冻结。
对于较大的n
值,这会冻结您的浏览器:
for (i = 0; i < n; i++){
//dosomething();
}
另一方面,这会降低您的速度,但不会锁定浏览器:
(function iterate(i) {
if (i < n) {
//dosomething();
setTimeout(function () {
iterate(++i);
}, 0);
}
})(0)