首页 > 解决方案 > 每次为动态创建的表获取更新的列数

问题描述

我有一个动态生成的表,带有一个过滤器来选择哪些列是可见的。我需要动态计数表中可见的列,然后将其输入代码的另一部分,但是,当我更改过滤器可见的列时,我使用的计数编码不会更新计数。

我尝试了两种方法来获取列数:

1) 选择的列过滤器选项计数:

jQuery(document).ready(function ($) {
        var OptionSelected = $("#ColumnCheckbox option:selected").length;
    console.log(OptionSelected);
    });

2)列头数:

jQuery(document).ready(function ($) {
        var ColumnsSelected = $("table.CompTable thead > tr > th:not(:first)").length;
    console.log(ColumnsSelected);
    });

但是,在这两种情况下,过滤列时计数都不会改变。(计数显示在下面工作代码的“控制台”中)

有没有其他方法可以让计数在每次列增加和减少时动态变化?

完整的工作代码如下:

jQuery(document).ready(function($) {
var StatJSON = {
   "Samsung": {
    "Ranking": '#3',
    "Rating": '2.5',
    "Distance": '30',
    "Time to Travel": '400',
    "Altitude (meter)": '200',
    "Area": '250'
    },
  "Mi": {
    "Ranking": '#2',
    "Rating": '3.5',
    "Distance": '20',
    "Time to Travel": '150',
    "Altitude (meter)": '0',
    "Area": 'NA'
    },
  "Apple": {
    "Ranking": '#1',
    "Rating": '4.5',
    "Distance": '50',
    "Time to Travel": '300',
    "Altitude (meter)": 'NA',
    "Area": '200'
    },
    "LG": {
    "Ranking": '#1',
    "Rating": '4.5',
    "Distance": '50',
    "Time to Travel": '300',
    "Altitude (meter)": 'NA',
    "Area": '200'
    }
};

jQuery('#btnSubmit').click(function() {
 var data = [];  
 jQuery("#selection").find(':selected').each(function(e) {
   var this_input = jQuery(this);
   if (this_input.is(':selected')) {
     data.push(this_input.val());
   }
 });
 $('#divResult').empty().append(PrintTable(data));

jQuery(document).ready(function ($) {

  jQuery('#divResult table tbody tr').find("td:first").each(function ($) {
        jQuery(this).addClass(((this.textContent).split(" ").join("").replace('#','').replace(/[()]/g, '')).replace(/ /g, ''));
        jQuery(this).siblings('td').addClass(((this.textContent).split(" ").join("").replace('#','').replace(/[()]/g, '')).replace(/ /g, ''));
        jQuery(this).parent('tr').addClass(((this.textContent).split(" ").join("").replace('#','').replace(/[()]/g, '')).replace(/ /g, ''));
    });

    jQuery('.divResult table th:not(:first)').each(function ($) {
        jQuery(this).addClass(jQuery(this).text().split(" ").join(""));
        jQuery(this).attr("name", this.textContent.split(" ").join(""));
    });
    jQuery('.divResult table th:first-child').removeClass;
    jQuery('.divResult table th:first-child').removeAttr('name');
    jQuery('table thead th[class]').each(function () {
        $('table tbody td:nth-child(' + ($(this).index() + 1) + ')').addClass(this.className)
    });

    jQuery(document).ready(function ($) {
        var data = [];
        
        jQuery('#divResult table thead th:not(:first)').each(function () {
            data.push(jQuery(this).text());
            
            function Column(data) {
                var html='';
                jQuery.each(data, function(index, value){
                    html += '<option selected name="' + value + '" class="' + value.split(" ").join("").replace('#','').replace(/[()]/g, '').replace(/ /g, '') + '" >' + value + '</option>'
            });
            return html;
            }
            
        jQuery('#ColumnCheckbox').empty().append(Column(data));
        });
    });

    jQuery('#FilterDiv').show();

    $("#ColumnCheckbox").change(function() {
        var options = $(this).find("option");
        var OptionSelected = $(this).find("option").prop("selected");
        $.each(options,function(i,val){
            var selected = $(this).prop("selected");
            var currentClass = $(this).attr("class");
            if(selected == false){
                $("table.CompTable thead tr th." + currentClass).hide();
                $("table.CompTable tbody tr td." + currentClass).hide();
            }else{
                $("table.CompTable thead tr th." + currentClass).show();
                $("table.CompTable tbody tr td." + currentClass).show();
            }
        });
    });

    jQuery(document).ready(function ($) {
        var OptionSelected = $("#ColumnCheckbox option:selected").length;
    console.log(OptionSelected);
    });

    jQuery(document).ready(function ($) {
        var ColumnsSelected = $("table.CompTable thead > tr > th:not(:first)").length;
    console.log(ColumnsSelected);
    });
    

});

});

function PrintTable(data) {
  var html = '<table id="CompTable" class="CompTable"><thead><tr>';
  if (data && data.length) {
    html += '<th>&nbsp;</th>';
    jQuery.each(data, function(k, v) {
      html += '<th>' + v + '</th>';
    });
    html += '</tr></thead>';
    html += '<tbody>';
    jQuery.each(StatJSON[data[0]], function(k, v) {
      html += '<tr><td>' + k + '</td>';
        jQuery.each(data, function(k2, v2) {
        html += '<td>' + StatJSON[data[k2]][k] + '</td>';
      });
      html += '</tr>';
    });
  } else { html += 'No results found</td></tr>'; }
  html += '</table>';
  return html;
}

});

jQuery(function($) {
	$.fn.select2.amd.require([
    'select2/selection/single',
    'select2/selection/placeholder',
    'select2/selection/allowClear',
    'select2/dropdown',
    'select2/dropdown/search',
    'select2/dropdown/attachBody',
    'select2/utils'
  ], function (SingleSelection, Placeholder, AllowClear, Dropdown, DropdownSearch, AttachBody, Utils) {

	var SelectionAdapter = Utils.Decorate(
      SingleSelection,
      Placeholder
    );
    
    SelectionAdapter = Utils.Decorate(
      SelectionAdapter,
      AllowClear
    );
          
    var DropdownAdapter = Utils.Decorate(
      Utils.Decorate(
        Dropdown,
        DropdownSearch
      ),
      AttachBody
    );
    
	var ColumnSelected = $('#ColumnCheckbox')
    $(ColumnSelected).select2({
      width: '40%',
      placeholder: 'Select multiple items',
      selectionAdapter: SelectionAdapter,
      dropdownAdapter: DropdownAdapter,
      allowClear: true,
      templateResult: function (data) {

        if (!data.id) { return data.text; }

        var $res = $('<div></div>');

        $res.text(data.text);
        $res.addClass('wrap');

        return $res;
      },
      templateSelection: function (data) {
      	if (!data.id) { return data.text; }
        var ColumnselectedNumber = ($(ColumnSelected).val() || []).length;
        var ColumnSelectedElements = $(ColumnSelected).val();
        var total = $('option', $(ColumnSelected)).length;
        return "Selected " + ColumnselectedNumber + " of " + total;
      }
    });
  
  });
  
});
.CompTable {
  table-layout: fixed;
  width: 50%;
  position: relative;
  font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
  margin: 10px;
  border: 1px solid #222;
  text-align: center;
}
.select2-results__option .wrap:before{
    font-family:fontAwesome;
    color:#999;
    content:"\f096";
    width:25px;
    height:25px;
    padding-right: 10px;
    
}
.select2-results__option[aria-selected=true] .wrap:before{
    content:"\f14a";
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>


Options:
<select id="selection" select class="js-example-basic-multiple" multiple="multiple">
        <option value="Samsung">Samsung</option>
        <option value="Mi">Mi</option>
        <option value="Apple">Apple</option>
        <option value="LG">LG</option>
</select>
<br /><br />
<input id="btnSubmit" class="button" type="submit" value="submit"/>
    <br /><br />
<div id="FilterDiv" style="display: none;">

<select multiple id="ColumnCheckbox"></select>
</div>

<div id="divResult" class="divResult"></div>

标签: javascriptjqueryhtmlfilterhtml-table

解决方案


推荐阅读