代码之家  ›  专栏  ›  技术社区  ›  TheWebs

如何将此代码转换为一个函数jquery

  •  0
  • TheWebs  · 技术社区  · 6 年前

    考虑以下狙击:

    $('#num-locations input[type="checkbox"]').on('click', function(e) {
      var checkedInputs = $("#num-locations input[type=checkbox]:checked");
      var manageWrappers = $(".manage-wrapper");
    
      manageWrappers.removeClass("hide-on-check");
      if (!checkedInputs.length) return;
    
      var locations = checkedInputs.map(function() { return $(this).data("location") }).get();
    
      manageWrappers
        .filter(function() {
          return !locations.includes($(this).data("city"));
        }).addClass("hide-on-check");
    });
    
    
    $('#num-cities input[type="checkbox"]').on('click', function(e) {
      var checkedInputs = $("#num-cities input[type=checkbox]:checked");
      var manageWrappers = $(".manage-wrapper");
    
      manageWrappers.removeClass("hide-on-check");
      if (!checkedInputs.length) return;
    
      var cities = checkedInputs.map(function() { return $(this).data("city") }).get();
    
      manageWrappers
        .filter(function() {
          return !cities.includes($(this).data("city"));
        }).addClass("hide-on-check");
    });
    
    $('#num-provinces input[type="checkbox"]').on('click', function(e) {
      var checkedInputs = $("#num-provinces input[type=checkbox]:checked");
      var manageWrappers = $(".manage-wrapper");
    
      manageWrappers.removeClass("hide-on-check");
      if (!checkedInputs.length) return;
    
      var provinces = checkedInputs.map(function() { return $(this).data("province") }).get();
    
      manageWrappers
        .filter(function() {
          return !provinces.includes($(this).data("province"));
        }).addClass("hide-on-check");
    });
    

    每一个都是我想让他们做的,有一些小故障。例如,如果您选中一个复选框或两个或三个或曾经在 #num-locations 然后有一对 #num-provinces 你的位置被重新设置并取消了标识。

    其目标是将此功能添加到一个“已检查”的位置、城市或省份数组中,然后隐藏 manageWrappers 基于单击的内容并显示未单击的内容。

    我不确定如何在一个函数中观察多个点击事件,因此我在这里询问的原因是什么。

    有什么想法吗?

    1 回复  |  直到 6 年前
        1
  •  1
  •   fdomn-m    6 年前

    我不确定如何在一个函数中观察多个点击事件

    这个 .on("click"... 应用于选择器中的所有元素,若要选择多个元素,请用逗号分隔它们 , ,代码的初始更新为:

    $('#num-cities input[type="checkbox"],#num-provinces input[type="checkbox"]').on('click', function(e) {
        var checkedInputs = $(this).filter(":checked");
    

    您将需要进行其他更改才能成为单个函数,但这将回答所问的问题。