简体   繁体   English

替换表而不是 append jquery

[英]Replace table instead of append jquery

I have the following code segment that grabs user input from an HTML form, and then reads a CSV file, and grabs corresponding data to display to my website.我有以下代码段,从 HTML 表单中获取用户输入,然后读取 CSV 文件,并获取相应的数据以显示到我的网站。 If I submit another 'searchTerm' after the initial one in my form, it appends the new row of data from the csv file to the page, and I want it to replace instead.如果我在表单中的第一个“searchTerm”之后提交另一个“searchTerm”,它会将 csv 文件中的新数据行附加到页面,而我希望它被替换。 When I try to replace the row however, all my data vanishes.但是,当我尝试替换该行时,我所有的数据都消失了。

function submitForm(){
    nameValue = document.getElementById("searchTerm").value;

    //document.getElementById("display-results").innerHTML = nameValue;
    location.href = "#page-3";

    function arrayToTable(tableData) {
        var table = $('<table></table>');
        $(tableData).each(function (i, rowData) {
            var row = $('<tr></tr>');
            
            $(rowData).each(function (j, cellData) {
              if (cellData == nameValue) {
                row.append($('<td>'+rowData[1]+'</td>'));
              }
            });
            table.append(row);
        });
        return table;
    }

    $.ajax({
        type: "GET",
        url: "mainFile.csv",
        success: function (data) {
            parsed = Papa.parse(data).data;
            $('#display-results').append(arrayToTable(Papa.parse(data).data));
        }
    });
}

As you can see in the image, it appends the content rather than replacing the first array.正如您在图像中看到的,它附加内容而不是替换第一个数组。

这是我的代码如何执行的一个简单示例,它附加了一行新数据而不是替换旧数据。

Remember to just replace the table, not the entire display-results element (except the first time you build the table).请记住只替换表格,而不是整个显示结果元素(第一次构建表格时除外)。


if($('#display-results table').length === 0) // append if you haven't built the table yet
  $('#display-results').append(arrayToTable(Papa.parse(data).data));
else
  $('#display-results table').replaceWith(arrayToTable(Papa.parse(data).data));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM