在JavaScript/jQuery中从列中获取不重复的所有值
我想创建一个选择下拉列表,其中包含一列中的所有值,每个值只显示一次在JavaScript/jQuery中从列中获取不重复的所有值,javascript,jquery,html,select,Javascript,Jquery,Html,Select,我想创建一个选择下拉列表,其中包含一列中的所有值,每个值只显示一次 假设我有一个基本的HTML表,并且所讨论的列是columnA,有没有办法在JavaScript或jQuery中实现这一点?您必须进行一些检查,以确保尚未包含列,例如: function makeSelectFromColumn() { var arr = []; $("td:first").each(function() { if ($.inArray($(this).text(), arr) =
假设我有一个基本的HTML表,并且所讨论的列是columnA,有没有办法在JavaScript或jQuery中实现这一点?您必须进行一些检查,以确保尚未包含列,例如:
function makeSelectFromColumn() {
var arr = [];
$("td:first").each(function() {
if ($.inArray($(this).text(), arr) == -1)
arr.push($(this).text());
});
//Create your select
var select = $("<select />");
for (var i = 0; i < arr.length; i++) {
$("<option>" + arr[i] + "</option>").appendTo(select);
}
select.appendTo("body"); //append where you need
}
对于无库的普通js: html:
纯Javascript,ES6,简单:
const cells = [].slice.call(table.querySelectorAll('td.mycell')) //using slice to convert nodelist to array
const values = cells.map(cell => cell.textContent)
const distinct = [...new Set(values)]
一个专栏到底是什么样子的呢?非常感谢,很可能是重复的-这也很棒!我将尝试这两种方法,看看哪一种效果更好。@user2571510两种方法都很好,但没有理由仅为此使用jQuery。如果您已经在使用jQuery,那么最好使用jQuery解决方案。如果您没有使用jQuery,请使用我的方法。一般来说,我认为如果可能的话,最好给出不使用图书馆的答案。非常感谢-这太完美了!
<table>
<tbody>
<tr><td>Col A Val1</td></tr>
<tr><td>Col A Val2</td></tr>
<tr><td>Col A Val3</td></tr>
<tr><td>Col A Val1</td></tr>
<tr><td>Col A Val2</td></tr>
<tr><td>Col A Val3</td></tr>
</tbody>
</table>
function getNthColumn(n) {
var data = [],
i,
yourSelect,
unique;
$("#yourTable tr td:nth-child("+n+")").each(function () {
data.push($(this).text());
});
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
// Use this function if your table is not large as the time complexity is O(n^2)
unique = data.filter(function(item, i, arr) {
return i == arr.indexOf(item);
});
yourSelect = $('#yourSelect');
for (i = 0; i < unique.length; i += 1) {
yourSelect.append("<option>"+unique[i]+"</option>");
}
}
const cells = [].slice.call(table.querySelectorAll('td.mycell')) //using slice to convert nodelist to array
const values = cells.map(cell => cell.textContent)
const distinct = [...new Set(values)]