【问题标题】:jQuery Checkboxes to Populate Mutlidimensional Array用于填充多维数组的 jQuery 复选框
【发布时间】:2014-11-03 05:00:51
【问题描述】:

我有一个复选框列表:

<input type="checkbox" name="a" value="cb1" value2="value01" class="sort" />
<input type="checkbox" name="a" value="cb2" value2="value02" class="sort" />
<input type="checkbox" name="a" value="cb3" value2="value03" class="sort" />
<input type="checkbox" name="a" value="cb4" value2="value04" class="sort" />

我想做的是,当我打开或关闭这些时,它们会填充一个多维数组 (Arr_Sort[0][1]),只有两个级别。

这是我的脚本代码,可以很好地填充一维数组,我只是不知道如何修改它来填充多维数组。

$(document).ready(function(){

    $(".sort").change(function()
    {
        var arr_sort = new Array();

        $(".sort").each(function()
        {
            if( $(this).is(':checked') )
            {
                arr_sort.push($(this).val());
            }
        });
        alert( arr_sort );
    });
});

【问题讨论】:

  • 我不明白你想用什么来填充你的多维数组。简单的数组是清楚的,但在多?提供有关您希望它的外观的其他信息
  • Arr_Sort[0][1] 的值应该是多少?
  • 我希望 Arr_Sort 是 [["cb1", "value01"], ["cb2", "value02"], ["cb3","value03"], ["cb4","值04"]]

标签: jquery html checkbox multidimensional-array populate


【解决方案1】:
 $(document).ready(function(){
var arr_sort = [];
    $(".sort").change(function(){
        $(this).each(function(key,val){
            if( $(this).is(':checked') ){
                arr_sort[ $(this).index() + 1] = $(this).val();
            }else{
                arr_sort.remove($(this).val());
            }
        });
        console.log( arr_sort );
    });
});

Array.prototype.remove = function() {
    var what, a = arguments, L = a.length, ax;
    while (L && this.length) {
        what = a[--L];
        while ((ax = this.indexOf(what)) !== -1) {
            this.splice(ax, 1);
        }
    }
    return this;
};
  1. 将 ARRAY 声明为 [] 以提高性能。
  2. 声明数组超出变化函数。
  3. 也处理负面情况,如果该值被删除,它应该从数组中删除。

【讨论】:

    【解决方案2】:

    尝试替换arr_sort.push( $( this ).val() );

    arr_sort.push( new Array( $( this ).val(), $( this ).attr( 'value2' ) ) );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-15
      • 1970-01-01
      • 2011-11-07
      • 1970-01-01
      • 2018-05-07
      • 2011-01-11
      相关资源
      最近更新 更多