如何优化我的JavaScript并减少我所做的“$ .fn.not(...)”调用量?

时间:2017-06-22 23:37:54

标签: jquery

我有一个JavaScript文件,我在其中至少调用了$.fn.not(...);函数 如何出于同样的原因优化我的代码并阻止多次调用相同的函数?

这是我的JS:

$(document).ready(function() {
  var ba = ".form_elem_program option[value='Business Administration']";
  var cjc = ".form_elem_program option[value='Criminal Justice: Corrections']";
  var cm = ".form_elem_program option[value='Construction Management']";
  var da = ".form_elem_program option[value='Dental Assisting']";
  var dh = ".form_elem_program option[value='Dental Hygiene']";
  var dms = ".form_elem_program option[value='Diagnostic Medical Sonography']";
  var ma = ".form_elem_program option[value='Medical Assisting']";
  var mo = ".form_elem_program option[value='Medical Office']";
  var pt = ".form_elem_program option[value='Pharmacy Technology']";
  var rt = ".form_elem_program option[value='Respiratory Therapy']";
  var rn = ".form_elem_program option[value='Registered Nursing']";
  var st = ".form_elem_program option[value='Surgical Technology']";
  var vt = ".form_elem_program option[value='Veterinary Technology']";
  var vn = ".form_elem_program option[value='Vocational Nursing']";
  var amt = ".form_elem_program option[value='Aviation Maintenance Technology']";
  var et = ".form_elem_program option[value='Electrical Technology']";
  var hvac = ".form_elem_program option[value='Heating, Ventilation, Air Conditioning - Refrigeration Technology']";
  var imt = ".form_elem_program option[value='Industrial Maintenance Technology']";
  if (campus == "visalia") {
    // XXX: this is the "problem code":
    $('#program').children().not(":first").not(ba).not(cjc).not(da).not(dh).not(ma).not(mo).not(pt).not(rt).not(rn).not(vn).not(hvac).not(imt).remove();
  }
  if (campus == "porterville") {
    // XXX: this is the "problem code":
    $('#program').children().not(":first").not(ba).not(ma).not(mo).remove();
  }
});

3 个答案:

答案 0 :(得分:0)

可能的方法是:

var elems = $('#program').children().not(":first");
if (campus == "visalia") {
  [ba, cjc, da, dh, ma, mo, pt, rt, rn, v, hvac, imt].forEach(function(e) {
    elems = elems.not(e);
  });
}
if (campus == "porterville") {
  [ba, ma, mo].forEach(function(e) {
    elems = elems.not(e);
  });
}
elems.remove();

答案 1 :(得分:0)

我通过使用要忽略的选项值数组生成所需的选择器来简化脚本 意思是;而不是字面上重复相同的字符串&一遍又一遍地调用相同的函数你只能使用一个动态创建的单个选择器调用$.fn.not(...);函数。
这可以确保您的JS不会陷入困境,并且您的网站性能不会受到相同字符串和/或函数调用的数十次重复的影响。

以下是您的简化代码:

jQuery(document).ready(function($) {
  // create the selectors
  var cs = function(group) {
    // prepare the result string
    var result = "";
    // loop through the option value groups
    for(var i = 0; i < group.length; i++) {
      result += ".form_elem_program option[value='" + group[i] + "'],";
    }
    // return the generated selector
    return result;
  };

  // handle the first selector group
  if(campus == "visalia") {
    $("#program").children().not(":first").not(cs([
      "Business Administration","Medical Assisting","Medical Office"
    ])).remove();
  }

  // handle the second selector group
  else if(campus == "porterville") {
    $("#program").children().not(":first").not(cs([
      "Business Administration", "Medical Assisting", "Medical Office", "Criminal Justice: Corrections",
      "Construction Management", "Dental Assisting", "Dental Hygiene", "Diagnostic Medical Sonography",
      "Pharmacy Technology", "Respiratory Therapy", "Registered Nursing", "Surgical Technology",
      "Veterinary Technology", "Vocational Nursing", "Aviation Maintenance Technology", "Electrical Technology",
      "Heating, Ventilation, Air Conditioning - Refrigeration Technology", "Industrial Maintenance Technology",
    ])).remove();
  }
});

另一种方法是使用函数将每个选项值注入选择器字符串,然后使用$.each(..., ...);忽略每个 not 选择器,如下所示:

jQuery(document).ready(function($) {
  // generate a new selector
  var cs2 = function(value) {
    return ".form_elem_program option[value='" + value + "']";
  };
  // create the required selectors
  var ba = cs2("Business Administration"),
    cjc = cs2("Criminal Justice: Corrections"),
    cm = cs2("Construction Management"),
    da = cs2("Dental Assisting"),
    dh = cs2("Dental Hygiene"),
    dms = cs2("Diagnostic Medical Sonography"),
    ma = cs2("Medical Assisting"),
    mo = cs2("Medical Office"),
    pt = cs2("Pharmacy Technology"),
    rt = cs2("Respiratory Therapy"),
    rn = cs2("Registered Nursing"),
    st = cs2("Surgical Technology"),
    vt = cs2("Veterinary Technology"),
    vn = cs2("Vocational Nursing"),
    amt = cs2("Aviation Maintenance Technology"),
    et = cs2("Electrical Technology"),
    hvac = cs2("Heating, Ventilation, Air Conditioning - Refrigeration Technology"),
    imt = cs2("Industrial Maintenance Technology");

  // get the elements
  var elements = $("#program").children().not(":first");

  // handle the first selector group
  if (campus == "visalia") {
    $.each([ba, cjc, da, dh, ma, mo, pt, rt, rn, v, hvac, imt], function(i, element) {
      elements = elements.not(element);
    });
  }

  // handle the second selector group
  else if (campus == "porterville") {
    $.each([ba, ma, mo], function(i, element) {
      elements = elements.not(element);
    });
  }
});
祝你好运,万事如意!

答案 2 :(得分:0)

我在@Mango和@Isac的答案中提出了建议,最后得到了以下代码。我需要使用$.each()方法来运行所有$.not()方法。

这允许我使用数组和对象来进一步简化代码。我们的计划和校园组合不断变化,因此可维护性对于此代码至关重要。

// generate a new selector
var fieldOption = function(value) {
  return ".form_elem_program option[value='" + value + "']";
};
// create the required selectors for each program
var ba   = fieldOption("Business Administration"),
    cjc  = fieldOption("Criminal Justice: Corrections"),
    // there are more programs not included for simplicity of answer
    imt  = fieldOption("Industrial Maintenance Technology"),
    it   = fieldOption("Information Technology");

// create object with array of selectors of the campus programs
var campusPrograms = {
  visalia:          [ba, cjc, da, dh, ma, mo, pt, rt, rn, vn, hvac, imt],
  hanford:          [ba, ma, mo],
  // there are more campuses not included for simplicity of answer
  delano:           [ba, ma, mo],
  porterville:      [ba, ma, mo]
};

// run function to pull campus param from URL
var campusURL = getUrlParams()['campus'];
// get array from campusPrograms object
var programs = campusPrograms[campusURL];

// remove all programs except ones included in campus array
var elems = $('#program').children().not(":first");  

$.each(programs, function(index, value) {
  elems = elems.not(value);
});

elems.remove();