创建由JSON生成的可编辑表

时间:2013-06-14 07:53:27

标签: jquery json html-table

我有这个函数可以正确生成一些单词表:

function show(json) {
    var content = '<table id = "myTable" border = 1>';
    var counter;
    for (counter = 0; counter < json.length; counter++) {
        content += '<tr><td class = "topics">' + json[counter]['topic_name'] + '</td>'
        '</tr>';
    }
    content += '</table>';
    $('#table_here').append(content);
}

我想让这个表格可编辑,这样当用户点击表格上的单元格时,他应该编辑该单元格。所以我在网上教程的帮助下写了这篇文章:

function show(json) {
    var content = '<table id = "myTable" border = 1>';
    var counter;
    for (counter = 0; counter < json.length; counter++) {
        content += '<tr id =' + counter + ' class="edit_tr"><td class = "edit_td"><span id = "first_' + counter + '" class="text">' + json[counter]['topic_name'] + '</span><input type="text" value="' + json[counter]['topic_name'] + '" class="editbox"  id = "first_input_' + counter + '" /&gt;></td>'
        '</tr>';
    }
    content += '</table>';
    $('#table_here').append(content);
}

当我打开这个页面时,单元格中的单词和单元格中单词中的单词同时出现。当我点击页面上的某个地方时,框会消失,只剩下单词,但当我没有任何反应时点击这些单词。我怎样才能解决这个问题? 我从本教程中获取了代码:http://www.9lessons.info/2011/03/live-table-edit-with-jquery-and-ajax.html

2 个答案:

答案 0 :(得分:2)

我不知道你面临的错误,但这里是 demo 。在演示中,我使用了一系列颜色,如下所示:

[
 {
  "colorName": "red",
  "hexValue": "#f00"
 },
 {
   "colorName": "green",
   "hexValue": "#0f0"
 },
 .. so on
]

您需要两个点击功能:

  1. 单击颜色时显示文本框:

    $(document).on("click", ".edit_td", function () {
       //reset to default, hide every input and show span in table
       $("input:text").hide();
       $(".text").show();
       $(this).find("span").hide().end().find("input:text").show();
    });
    
  2. 隐藏文本框并在table

    以外的任何位置点击时显示范围
    $(document).on("click", function (event) {
      var $target = $(event.target);
      if ($target.closest("table").length == 0) {
        var $input = $("input:text:visible");
        var value = $input.val();
        $input.closest("td").find(".text").text(value).show();
        $input.parent().hide();
      }
    

    });

  3. 编辑:

    为附加的输入按钮添加了keyup处理程序:

    $(document).on("keyup", "input:text", function (e) {
      if (e.which === 13) {
        var value = $(this).val();
        $(this).closest("td").find(".text").html(value).show();
        $(this).parent().hide();
        return false;
      }
    });
    

    单击顶部的演示以查看更新:)

    希望这会有所帮助:)

答案 1 :(得分:1)

使用http://handsontable.com/简化的类似Excel的数据网格编辑器,用于HTML,JavaScript和jQuery的