【问题标题】:Convert D3 to JQuery to append a table将 D3 转换为 JQuery 以附加表
【发布时间】:2020-09-23 21:05:08
【问题描述】:

我正在开发一个需要使用 JQuery 和 Ajax 的项目。但是,我过去主要使用 D3.js,因此在我的代码中使用 D3 来动态附加表格。因为我不能真正将我的 D3 代码与 JQuery 混合,所以我需要在 JQuery 中附加一个表。

我需要先追加一行,然后选择该行,然后在该行追加'<td>' 标签并从数组中添加文本。我在D3中写了如下:

var tableArray = []
tableArray.push(string1, string2, string3, string4, string5)

var row = d3.select('tbody').append('tr');

tableArray.forEach(function(x) {

    var cell = row.append('td');
    cell.text(x);
});

如何在 JQuery 中做同样的事情?

【问题讨论】:

    标签: javascript jquery d3.js


    【解决方案1】:

    我的 jQuery 有点生疏了,但是下面的 sn-p 中的内容可以工作。要记住的最重要的事情是它们以不同的方式构造新元素(作为完整标记),并且附加不会返回附加的元素,它会返回附加到的选定元素。其他人也许可以为您提供更有效或更惯用的方法。

    var tableArray = []
    tableArray.push('string1', 'string2', 'string3', 'string4', 'string5')
    
    var tbody = $('tbody'); // get a reference to the existing tbody by CSS selector
    var row = $('<tr/>'); // construct a tr element
    
    tableArray.forEach(function(x) { // before appending to the tbody...
        var cell = ('<td>' + x + '</td>'); // construct your cells with the text inline
        row.append(cell); // and append to the row
    });
    
    tbody.append(row); // finally, append your row to the tbody
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <table><tbody></tbody></table>

    另外,FWIW,当我第一次开始使用 this jQuery cheat sheet(然后直接链接到文档)是一个非常有用的资源。

    【讨论】:

    • 这行得通!唯一的问题是它添加了 2 行而不是 1 行。我在不使用 Ajax 的情况下自己尝试了这个,但它总是添加 2 行相同的行。关于如何防止这种情况发生的任何建议?
    • 我解决了。它添加两行的原因是因为它插入了另一个 元素。我通过给 tbody 一个 id 来解决它,然后在代码中给它一个引用,如下所示: var tbody = $('#tbody');
    猜你喜欢
    • 2021-07-08
    • 2019-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-18
    • 1970-01-01
    • 2020-07-31
    • 2015-09-17
    相关资源
    最近更新 更多