You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

动态加载CSV生成HTML表格,下拉筛选第二列功能失效求助

问题:CSV表格筛选功能失效排查

我通过本地CSV文件动态生成了一个HTML表格,并添加了下拉列表,希望利用第二列的唯一值对表格进行筛选。目前表格可正常加载,下拉列表也能正确加载第二列的唯一值,但筛选功能无法正常工作。请问我可能遗漏了什么?

原代码如下:

<!DOCTYPE html>
<html>
<head>
    <title>CSV Table with Filter</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            var table = null;

            // Function to filter the table based on the selected option
            function filterTable(selectedOption) {
                // Show all rows initially
                table.find("tr").show();

                // Hide rows that do not match the selected option
                if (selectedOption !== "All") {
                    table.find("tr:not(:has(th))").each(function() {
                        var cellValue = $(this).find("td:eq(0)").text();
                        if (cellValue !== selectedOption) {
                            $(this).hide();
                        }
                    });
                }
            }

            // Load the CSV data and create the table
            $.ajax({
                type: "GET",
                url: "data/data.csv",
                dataType: "text",
                success: function(data) {
                    var rows = data.split("\n");
                    table = $("<table />");
                    for (var i = 0; i < rows.length; i++) {
                        var cells = rows[i].split(",");
                        if (i === 0) {
                            var headerRow = $("<tr />");
                            for (var j = 0; j < cells.length; j++) {
                                headerRow.append($("<th />").text(cells[j]));
                            }
                            table.append(headerRow);
                        } else {
                            var row = $("<tr />");
                            for (var k = 0; k < cells.length; k++) {
                                row.append($("<td />").text(cells[k]));
                            }
                            table.append(row);
                        }
                    }
                    $("#csvTable").append(table);

                    // Populate the dropdown with unique values from the first column
                    var options = [];
                    table.find("tr:not(:has(th))").each(function() {
                        var cellValue = $(this).find("td:eq(1)").text();
                        if ($.inArray(cellValue, options) === -1) {
                            options.push(cellValue);
                        }
                    });
                    $("#filterSelect").append($("<option />").val("All").text("All"));
                    $.each(options, function(index, value) {
                        $("#filterSelect").append($("<option />").val(value).text(value));
                    });

                    // Add event listener to the dropdown
                    $("#filterSelect").change(function() {
                        filterTable($(this).val());
                    });
                }
            });
        });
    </script>
</head>
<body>
    <div>
        <label for="filterSelect">Filter by:</label>
        <select id="filterSelect"></select>
    </div>
    <div id="csvTable"></div>
</body>
</html>

问题原因与修复方案

1. 核心问题:列索引不匹配

你在填充下拉列表时,提取的是第二列(td:eq(1))的唯一值,但在筛选函数filterTable中,却错误地判断第一列(td:eq(0))的内容,导致筛选逻辑完全错位。

修改filterTable函数中的列索引,将td:eq(0)改为td:eq(1)即可解决:

function filterTable(selectedOption) {
    // Show all rows initially
    table.find("tr").show();

    // Hide rows that do not match the selected option
    if (selectedOption !== "All") {
        table.find("tr:not(:has(th))").each(function() {
            // 修改此处的索引为1,对应第二列
            var cellValue = $(this).find("td:eq(1)").text();
            if (cellValue !== selectedOption) {
                $(this).hide();
            }
        });
    }
}

2. 额外优化:CSV解析的鲁棒性(可选)

直接用split(",")拆分CSV存在缺陷,如果单元格内容包含逗号(比如带引号的"Doe, John"),会导致拆分错误。如果需要处理这类场景,可以使用更可靠的CSV解析逻辑,比如:

function parseCSV(csv) {
    var lines = csv.split("\n");
    var result = [];
    var pattern = /(".*?"|[^",]+)(?=\s*,|\s*$)/g;
    lines.forEach(function(line) {
        var cells = [];
        var match;
        while ((match = pattern.exec(line)) !== null) {
            cells.push(match[1].replace(/^"|"$/g, ""));
        }
        result.push(cells);
    });
    return result;
}

在AJAX成功回调中替换原有的拆分逻辑:

var rows = parseCSV(data);

修复后的完整代码

<!DOCTYPE html>
<html>
<head>
    <title>CSV Table with Filter</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            var table = null;

            // Function to filter the table based on the selected option
            function filterTable(selectedOption) {
                // Show all rows initially
                table.find("tr").show();

                // Hide rows that do not match the selected option
                if (selectedOption !== "All") {
                    table.find("tr:not(:has(th))").each(function() {
                        var cellValue = $(this).find("td:eq(1)").text();
                        if (cellValue !== selectedOption) {
                            $(this).hide();
                        }
                    });
                }
            }

            // Load the CSV data and create the table
            $.ajax({
                type: "GET",
                url: "data/data.csv",
                dataType: "text",
                success: function(data) {
                    var rows = data.split("\n");
                    table = $("<table />");
                    for (var i = 0; i < rows.length; i++) {
                        var cells = rows[i].split(",");
                        if (i === 0) {
                            var headerRow = $("<tr />");
                            for (var j = 0; j < cells.length; j++) {
                                headerRow.append($("<th />").text(cells[j]));
                            }
                            table.append(headerRow);
                        } else {
                            var row = $("<tr />");
                            for (var k = 0; k < cells.length; k++) {
                                row.append($("<td />").text(cells[k]));
                            }
                            table.append(row);
                        }
                    }
                    $("#csvTable").append(table);

                    // Populate the dropdown with unique values from the second column
                    var options = [];
                    table.find("tr:not(:has(th))").each(function() {
                        var cellValue = $(this).find("td:eq(1)").text();
                        if ($.inArray(cellValue, options) === -1) {
                            options.push(cellValue);
                        }
                    });
                    $("#filterSelect").append($("<option />").val("All").text("All"));
                    $.each(options, function(index, value) {
                        $("#filterSelect").append($("<option />").val(value).text(value));
                    });

                    // Add event listener to the dropdown
                    $("#filterSelect").change(function() {
                        filterTable($(this).val());
                    });
                }
            });
        });
    </script>
</head>
<body>
    <div>
        <label for="filterSelect">Filter by:</label>
        <select id="filterSelect"></select>
    </div>
    <div id="csvTable"></div>
</body>
</html>

内容的提问来源于stack exchange,提问作者rafad1

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 22:44:59