使用 jQuery 编辑单个表格单元格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1224729/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:57:28  来源:igfitidea点击:

Using jQuery to edit individual table cells

jqueryhtmlhtml-table

提问by mrpatg

How can I use jQuery to click on a table cell and edit its contents. There is a particular column which contains several paragraphs of data, so if possible, have a pop up window with a large text area (or ideally an HTML editor).

如何使用 jQuery 单击表格单元格并编辑其内容。有一个包含几段数据的特定列,因此如果可能,请使用带有大文本区域的弹出窗口(或理想情况下的 HTML 编辑器)。

The changes need only be superficial as I am using another jQuery plugin to scrape the table contents and export it to something else.

更改只需要很肤浅,因为我正在使用另一个 jQuery 插件来抓取表格内容并将其导出到其他内容。

Difficulty, none of the cells can have unique names or id's.

困难的是,没有一个单元格可以有唯一的名称或 ID。

采纳答案by Daniel Moura

You may want to check the jqGridplugin.

您可能需要检查jqGrid插件。

回答by Andrew

I use Data tables (a jQuery plugin)as this makes everything so much simpler.

我使用数据表(一个 jQuery 插件),因为这让一切变得更加简单。

They also say to use the jEditable plugin with their plugin. Allows for rows to become editable: Link: Editable Table(includes code sample)

他们还说在他们的插件中使用 jEditable 插件。允许行变得可编辑:链接:可编辑表(包括代码示例)

回答by Strixy

Seeing as how this page is both 3 years old and the first result in a Google search I thought it was due a more current answer. Given the weight and complexity of the plugin options above I thought a simpler, no-frills, more direct solution might also be appreciated for those looking for alternatives.

看到这个页面已经 3 年了,而且是 Google 搜索中的第一个结果,我认为这是一个更新的答案。鉴于上述插件选项的重量和复杂性,我认为对于那些寻找替代方案的人来说,一个更简单、简洁、更直接的解决方案也可能会受到赞赏。

This replaces the table cell with a text input and calls custom events so you can handle whatever use case you want on save, close, blur, etc...

这将用文本输入替换表格单元格并调用自定义事件,以便您可以处理保存、关闭、模糊等所需的任何用例...

In this case the only way to change the information in the cell is to press enter, but you can customize that if you like, eg. you might want to save on blur.

在这种情况下,更改单元格中信息的唯一方法是按 Enter,但您可以根据需要自定义,例如。你可能想节省模糊。

In this example you can also press the Esc key to stop editing and put the cell back to what it was. You can customize that if you like.

在本例中,您还可以按 Esc 键停止编辑并将单元格恢复原状。如果您愿意,您可以自定义它。

This example works on a single click, but some people prefer doubleclick, your choice.

此示例适用于单击,但有些人更喜欢双击,这是您的选择。

$.fn.makeEditable = function() {
  $(this).on('click',function(){
    if($(this).find('input').is(':focus')) return this;
    var cell = $(this);
    var content = $(this).html();
    $(this).html('<input type="text" value="' + $(this).html() + '" />')
      .find('input')
      .trigger('focus')
      .on({
        'blur': function(){
          $(this).trigger('closeEditable');
        },
        'keyup':function(e){
          if(e.which == '13'){ // enter
            $(this).trigger('saveEditable');
          } else if(e.which == '27'){ // escape
            $(this).trigger('closeEditable');
          }
        },
        'closeEditable':function(){
          cell.html(content);
        },
        'saveEditable':function(){
          content = $(this).val();
          $(this).trigger('closeEditable');
        }
    });
  });
return this;
}

You can selectively apply the editable cells by attaching them like so, or whatever makes sense for your case.

您可以通过像这样附加可编辑单元格或任何对您的情况有意义的方式来选择性地应用可编辑单元格。

$('.editable').makeEditable();

回答by markouuu

Try this simple solution:

试试这个简单的解决方案:

$(function () {
    $("td").dblclick(function () {
        var OriginalContent = $(this).text();

        var inputNewText = prompt("Enter new content for:", OriginalContent);

        if (inputNewText != null) {
            $(this).text(inputNewText)
        }
    });
});

回答by RaYell

jEditableplugin can help you edit your table in place.

jEditable插件可以帮助您就地编辑表格。

$(document).ready(function() {
    $('td').editable('http://www.example.com/save.php');
});

回答by Phil.Wheeler

Making content editable can be achieved with plugins like the jQuery Editableone. How easy this would be to translate onto a table with no ids though, I'm not sure.

使用jQuery Editable等插件可以实现内容可编辑。转换到没有 ID 的表格上有多容易,我不确定。

To traverse your table (and I'm assuming your table either has an ID of its own or is the only table on the page) would be reasonably straight-forward if you were able to get that plugin working:

遍历你的表(我假设你的表要么有自己的 ID,要么是页面上唯一的表)如果你能够让该插件工作,将会相当简单:

$('#myTable td').editable();

But that doesn't give you the rich text editor you're after. The other approach would be to forget that plugin and try using the jQuery UI dialog.

但这并没有给你你想要的富文本编辑器。另一种方法是忘记该插件并尝试使用 jQuery UI 对话框。

$('#myTable td').click(function(){
  $('myDialog').dialog('open');
});

Assuming you put a rich-text editor in that dialog, you could use $.ajax() to post the result to some service at the server end.

假设您在该对话框中放置了一个富文本编辑器,您可以使用 $.ajax() 将结果发布到服务器端的某个服务。

Finally, the jqGridmight be a good option for you, depending on the data that you want in your table.

最后,jqGrid对您来说可能是一个不错的选择,具体取决于您想要在表中使用的数据。

回答by Murat Kazanova

Inkedmn's code not functional as it is but it is the simplest way to do it as an idea: So check out the following working code based on his logic:

Inkedmn 的代码不能正常工作,但作为一个想法,这是实现它的最简单方法:因此,请根据他的逻辑查看以下工作代码:

$(function() {
    $('#overlay').hide();
    $('td').click(function(event) {
        var myText = '';
        $('#overlay').show();
        var o = $(this);
        $('#closeLink').click(function(event) {
            event.preventDefault();
            myText = $('#overlay textarea').val();
            $(o).html(myText);
            $(this).parent().hide(500);
        });                  
    });
});

回答by inkedmn

$("td").click(function(event){
    var myText = '';
    $("myOverlayThing").show();
    $("myOverlayThingCloseLink").click(function(event){
        event.preventDefault();
        myText = $("myOverlayThing.textarea").val();
    });
    $(this).html(myText);
});

Probably a little more complicated than that, but that's the basic idea without seeing your HTML.

可能比这更复杂一点,但这是没有看到您的 HTML 的基本想法。

回答by Mahmoud Sayed

this is actually so straight forward, this is my HTML, jQuery sample.. and it works like a charm, I build all the code using an online json data sample. cheers

这实际上非常简单,这是我的 HTML、jQuery 示例..它的工作原理很吸引人,我使用在线 json 数据示例构建了所有代码。干杯

<< HTML >>

<< HTML >>

<table id="myTable"></table>

<< jQuery >>

<< jQuery >>

<script>
        var url = 'http://jsonplaceholder.typicode.com/posts';
        var currentEditedIndex = -1;
        $(document).ready(function () {
            $.getJSON(url, function (json) {
                var tr;
                tr = $('<tr/>');
                tr.append("<td>ID</td>");
                tr.append("<td>userId</td>");
                tr.append("<td>title</td>");
                tr.append("<td>body</td>");
                tr.append("<td>edit</td>");
                $('#myTable').append(tr);

                for (var i = 0; i < json.length; i++) {
                    tr = $('<tr/>');
                    tr.append("<td>" + json[i].id + "</td>");
                    tr.append("<td>" + json[i].userId + "</td>");
                    tr.append("<td>" + json[i].title + "</td>");
                    tr.append("<td>" + json[i].body + "</td>");
                    tr.append("<td><input type='button' value='edit' id='edit' onclick='myfunc(" + i + ")' /></td>");
                    $('#myTable').append(tr);
                }
            });


        });


        function myfunc(rowindex) {

            rowindex++;
            console.log(currentEditedIndex)
            if (currentEditedIndex != -1) {  //not first time to click
                cancelClick(rowindex)
            }
            else {
                cancelClick(currentEditedIndex)
            }

            currentEditedIndex = rowindex; //update the global variable to current edit location

            //get cells values
            var cell1 = ($("#myTable tr:eq(" + (rowindex) + ") td:eq(0)").text());
            var cell2 = ($("#myTable tr:eq(" + (rowindex) + ") td:eq(1)").text());
            var cell3 = ($("#myTable tr:eq(" + (rowindex) + ") td:eq(2)").text());
            var cell4 = ($("#myTable tr:eq(" + (rowindex) + ") td:eq(3)").text());

            //remove text from previous click


            //add a cancel button
            $("#myTable tr:eq(" + (rowindex) + ") td:eq(4)").append(" <input type='button' onclick='cancelClick("+rowindex+")' id='cancelBtn' value='Cancel'  />");
            $("#myTable tr:eq(" + (rowindex) + ") td:eq(4)").css("width", "200");

            //make it a text box
            $("#myTable tr:eq(" + (rowindex) + ") td:eq(0)").html(" <input type='text' id='mycustomid' value='" + cell1 + "' style='width:30px' />");
            $("#myTable tr:eq(" + (rowindex) + ") td:eq(1)").html(" <input type='text' id='mycustomuserId' value='" + cell2 + "' style='width:30px' />");
            $("#myTable tr:eq(" + (rowindex) + ") td:eq(2)").html(" <input type='text' id='mycustomtitle' value='" + cell3 + "' style='width:130px' />");
            $("#myTable tr:eq(" + (rowindex) + ") td:eq(3)").html(" <input type='text' id='mycustomedit' value='" + cell4 + "' style='width:400px' />");

        }

        //on cancel, remove the controls and remove the cancel btn
        function cancelClick(indx)
        {

            //console.log('edit is at row>> rowindex:' + currentEditedIndex);
            indx = currentEditedIndex;

            var cell1 = ($("#myTable #mycustomid").val());
            var cell2 = ($("#myTable #mycustomuserId").val());
            var cell3 = ($("#myTable #mycustomtitle").val());
            var cell4 = ($("#myTable #mycustomedit").val()); 

            $("#myTable tr:eq(" + (indx) + ") td:eq(0)").html(cell1);
            $("#myTable tr:eq(" + (indx) + ") td:eq(1)").html(cell2);
            $("#myTable tr:eq(" + (indx) + ") td:eq(2)").html(cell3);
            $("#myTable tr:eq(" + (indx) + ") td:eq(3)").html(cell4);
            $("#myTable tr:eq(" + (indx) + ") td:eq(4)").find('#cancelBtn').remove();
        }



    </script>

回答by HRJ

The JQuery Datatables Editableplugin seems to be better than the official Editable Table plugin, because the former supports in-line editing and is open-source.

JQuery的数据表可编辑插件似乎比官方可编辑的表格插件更好,因为在网上前者支持编辑和是开源的。