代码之家  ›  专栏  ›  技术社区  ›  Fishcake Richard

jquery从表列获取所有值

  •  19
  • Fishcake Richard  · 技术社区  · 17 年前

    我正在寻找一种方法,使用jQuery用表列中的唯一值填充选择框。到目前为止,我的尝试都是徒劳的,但我对前端开发还比较陌生,所以我希望有人能给我一些启示。

    2 回复  |  直到 17 年前
        1
  •  56
  •   foobarfuzzbizz    12 年前

    这应该让你开始。请注意,我将单元格内容用于选项的值和文本。你可能需要改变这一点,但从问题上看还不清楚。

    var items=[], options=[];
    
    //Iterate all td's in second column
    $('#tableId tbody tr td:nth-child(2)').each( function(){
       //add item to array
       items.push( $(this).text() );       
    });
    
    //restrict array to unique items
    var items = $.unique( items );
    
    //iterate unique array and build array of select options
    $.each( items, function(i, item){
        options.push('<option value="' + item + '">' + item + '</option>');
    })
    
    //finally empty the select and append the items from the array
    $('#selectId').empty().append( options.join() );
    
        2
  •  2
  •   TheVillageIdiot    17 年前

    function FillSelect(){
        var vals = new Array();
        var i=0;
        var options='';
        $("#tbl tr:gt(0) td:nth-child(2)").each(function(){
           var t=$(this).html();
           if($.inArray(t, vals) < 0)
           {
               vals[i]=t;
               i++;
           }
        });
    
        for(var j=0;j<i;j++)
        {
            options += '<option value="' + j + '">' + vals[j] + '</option>';
        }
    
        $("#sel2").html(options);
    }
    

    假设“tbl”是表的ID,“sel2”是要填充的select的ID。如果不想排除第一行,则可以删除 tr:gt(0) 简单地说 在选择器表达式中。