0

我在页面上有此代码循环,并且在选中选择框时会导致略有页面滞后。有没有办法优化代码?我对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");
            }
        }
    }
}
4

1 回答 1

1

通常,如果您的循环锁定了线程,您可以将其重构为使用超时调用的递归循环。这可以防止 UI 冻结。

对于较大的值n,这将冻结您的浏览器:

for (i = 0; i < n; i++){
    //dosomething();
}

另一方面,这会减慢您的速度,但不会锁定浏览器:

(function iterate(i) {
    if (i < n) {
        //dosomething();

        setTimeout(function () {
            iterate(++i);
        }, 0);
    }
})(0)
于 2013-03-22T02:29:46.997 回答