【问题标题】:Dynamically Create table from JSON and perform operations on columns after table has been generated从 JSON 动态创建表并在生成表后对列执行操作
【发布时间】:2018-01-10 04:54:30
【问题描述】:

我正在尝试创建一个通过 Ajax 调用获取 JSON 的动态表,并根据该数据创建一个表。我已经完成了这部分,但我的主要问题是,其中一个表列将是一个可编辑字段,它应该是通过 ajax 创建的不同列。

我真正的主要问题是如何告诉 JQuery 我希望它旁边的列更新。

<html>
<head>
<script src="jquery-3.2.1.min.js"></script>
<script src="jquery.dataTables.min.js"></script>
<script src="jquery.tabletojson.js"></script>
<link rel="stylesheet" type="text/css" href="jquery.dataTables.min.css"/>
</head>
<body>
    <table id="example" class="display" cellspacing="0" width="100%">
    <thead>
        <tr>
            <th>Name</th>
            <th>Position</th>
            <th>Office</th>
        </tr>
        <tbody></tbody>
    </thead>
<script>
$(document).ready(function() {
    $.get("objects.txt", function(response){
        var obj = jQuery.parseJSON(response);
        $.each(obj.data, function(key,value){
            $("#example tbody").append("<tr>");
            $("#example tbody").append("<td contenteditable=true>"+ value.name +"</td>");
            $("#example tbody").append("<td>" + value.position +"</td>")
            $("#example tbody").append("<td>" + value.Office +"</td>")
            $("#example tbody").append("</tr>");
        });
        //uses a table to json library
        var json = $("#example").tableToJSON();
    });
});

</script>
</body>

为简单起见,在编辑“名称”字段时,我希望编辑该行上的办公室字段。不完全确定从这里去哪里。 感谢您的帮助!

【问题讨论】:

  • DOM 是一个文档对象模型,而不是一堆 HTML 文本。没有仅附加“打开标签”或“关闭标签”之类的东西。您处理作为对象的整个元素。您可以从完整的 HTML 字符串创建这些元素对象。
  • @rockstar 谢谢你的回复,我想我真的不了解什么是 DOM。回到绘图板:)
  • 是的,当您弄清楚这一点时,事情会变得更有意义。但是想想一棵对象树。 document 在顶部,在 HTML 元素(引用为 documentElement)下,在 headbody 元素下,在这些元素下,它们各自的子元素,等等。因此,当您创建一个新元素时,您就是在创建一个对象,并将其作为该树结构中某处现有元素的新子元素。
  • 而 html 只是用来告诉浏览器如何创建这些对象。但是当你自己创建对象时,它们就是完整的元素

标签: javascript jquery json ajax


【解决方案1】:

尝试将整个&lt;tr&gt; 合并到一个追加调用中。

var obj = {
  data: [
    {
      name: "person 1",
      position: "President",
      Office: "Corner"
    },
    {
      name: "person 2",
      position: "Developer",
      Office: "Penthouse"
    },
  ]
};

$(document).ready(function() {
  $.each(obj.data, function(key,value){
    $("#example tbody").append("<tr><td contenteditable=true>"+ value.name +"</td><td>" + value.position +"</td><td>" + value.Office +"</td></tr>");
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
    <tr>
        <th>Name</th>
        <th>Position</th>
        <th>Office</th>
    </tr>
    <tbody></tbody>
</thead>
</table>

【讨论】:

  • 您好感谢您的回答,但问题不是关于如何创建动态创建的表,而是创建动态创建的表,其中一列将设置为 contenteditable。然后当用户在可编辑单元格中输入行单元格时,不同列中的值会发生变化。
  • 查看change 事件。有了它,您应该能够知道内容何时发生变化。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-11-12
  • 1970-01-01
  • 1970-01-01
  • 2020-05-30
  • 2020-08-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多