jquery 从表列中获取所有值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1237899/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:59:21  来源:igfitidea点击:

jquery get all values from table column

jqueryhtml

提问by Fishcake

I'm looking for a way to populate a select box with unique values from a table column using jQuery. So far my attempts have been futile but I am relatively new to front end development so I'm hoping someone can show me the light.

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

Cheers.

干杯。

回答by redsquare

This should get you started. Note that I use the cell contents for both the value and the text of the option. You may need to change this but it is unclear from the question.

这应该让你开始。请注意,我将单元格内容用于选项的值和文本。您可能需要更改此设置,但问题中不清楚。

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() );

回答by TheVillageIdiot

you can use jquery's each function:

你可以使用 jquery 的 each 函数:

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);
}

suppose 'tbl' is ID of your table, 'sel2'is id of select you want to populate. If you don't want to exclude first row then you can remove tr:gt(0)and put simple trin selector expression.

假设 'tbl' 是您的表的 ID,'sel2' 是您要填充的选择的 ID。如果您不想排除第一行,那么您可以删除tr:gt(0)并将简单的tr放入选择器表达式中。