如何使用 jQuery 动态创建 HTML 表格?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18846253/
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 22:36:45  来源:igfitidea点击:

How do I create HTML table using jQuery dynamically?

javascriptjqueryhtml-table

提问by Java Questions

I am trying to create a HTML table like the following dynamically using jQuery:

我正在尝试使用 jQuery 动态创建如下所示的 HTML 表:

<table id='providersFormElementsTable'>
    <tr>
        <td>Nickname</td>
        <td><input type="text" id="nickname" name="nickname"></td>
    </tr>
    <tr>
        <td>CA Number</td>
        <td><input type="text" id="account" name="account"></td>
    </tr>
</table>

This is my actual table :

这是我的实际表:

<table border="0" cellpadding="0" width="100%" id='providersFormElementsTable'> </table>

This is the method which will create trand tdelements taking idand labelText:

这是将创建trtd元素采用idand 的方法labelText

function createFormElement(id, labelText) {
    // create a new textInputBox button using supplied parameters
    var textInputBox = $('<input />').attr({
        type: "text", id: id, name: id
    });
    // create a new textInputBox using supplied parameters
    var inputTypeLable = $('<label />').append(textInputBox).append(labelText);

    // append the new radio button and label
    $('#providersFormElementsTable').append(inputTypeLable).append('<br />');
}

I also have a value which will be shown as tool tip.

我还有一个值将显示为工具提示。

Please help me to create a table dynamically with tool tip and tr td.

请帮我动态创建一个表tool tip and tr td

EDIT:

编辑:

I have almost done with the following code:

我几乎完成了以下代码:

function createProviderFormFields(id, labelText,tooltip,regex) {
    var tr = '<tr>' ;
    // create a new textInputBox  
    var textInputBox = $('<input />').attr({
        type: "text",
        id: id, name: id,
        title: tooltip
    });  

    // create a new Label Text
    tr += '<td>' + labelText  + '</td>';
    tr += '<td>' + textInputBox + '</td>';  
    tr +='</tr>';
    return tr;
}

Here label is coming properly and the input box is not coming and it shows [object Object]where the text box has to come...

这里标签正确出现,输入框没有出现,它显示[object Object]文本框必须出现的位置......

When I printed the textInputBoxusing console.log, I get the following:

当我打印textInputBoxusing 时console.log,我得到以下信息:

[input#nickname, constructor: function, init: function, selector: "", jquery: "1.7.2", size: function…]

[input#nickname, constructor: function, init: function, selector: "", jquery: "1.7.2", size: function…]

What could be the issue?

可能是什么问题?

Thanks to @theghostofcwho showed me path... :)

感谢@theghostofc谁向我展示了路径... :)

采纳答案by Vivek Jain

You may use two options:

您可以使用两个选项:

  1. createElement
  2. InnerHTML
  1. 创建元素
  2. 内部HTML

Create Element is the fastest way (check here.):

创建元素是最快的方式(检查这里。):

$(document.createElement('table'));

InnerHTML is another popular approach:

InnerHTML 是另一种流行的方法:

$("#foo").append("<div>hello world</div>"); // Check similar for table too.

Check a real example on How to create a new table with rows using jQuery and wrap it inside div.

查看如何使用 jQuery 创建一个包含行的新表并将其包装在 div 中的真实示例。

There may be other approaches as well. Please use this as a starting point and not as a copy-paste solution.

也可能有其他方法。请将此作为起点,而不是作为复制粘贴解决方案。

Edit:

编辑:

Check Dynamic creation of table with DOM

使用 DOM检查动态创建表

Edit 2:

编辑2:

IMHO, you are mixing object and inner HTML. Let's try with a pure inner html approach:

恕我直言,您正在混合对象和内部 HTML。让我们尝试使用纯内部 html 方法:

function createProviderFormFields(id, labelText, tooltip, regex) {
    var tr = '<tr>' ;
         // create a new textInputBox  
           var textInputBox = '<input type="text" id="' + id + '" name="' + id + '" title="' + tooltip + '" />';  
        // create a new Label Text
            tr += '<td>' + labelText  + '</td>';
            tr += '<td>' + textInputBox + '</td>';  
    tr +='</tr>';
    return tr;
}

回答by Luke W

An example with a little less stringified html:

一个不那么字符串化的 html 的例子:

var container = $('#my-container'),
  table = $('<table>');

users.forEach(function(user) {
  var tr = $('<tr>');
  ['ID', 'Name', 'Address'].forEach(function(attr) {
    tr.append('<td>' + user[attr] + '</td>');
  });
  table.append(tr);
});

container.append(table);

回答by Fabricio

Here is a full example of what you are looking for:

这是您正在寻找的完整示例:

<html>
<head>
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script>
        $( document ).ready(function() {
            $("#providersFormElementsTable").html("<tr><td>Nickname</td><td><input type='text' id='nickname' name='nickname'></td></tr><tr><td>CA Number</td><td><input type='text' id='account' name='account'></td></tr>");
        });
    </script>
</head>

<body>
    <table border="0" cellpadding="0" width="100%" id='providersFormElementsTable'> </table>
</body>

回答by The Dark Knight

I understand you want to create stuff dynamically. That does not mean you have to actually construct DOM elements to do it. You can just make use of htmlto achieve what you want .

我了解您想动态创建内容。这并不意味着您必须实际构建 DOM 元素才能做到这一点。你可以利用html来实现你想要的。

Look at the code below :

看看下面的代码:

HTML:

HTML:

<table border="0" cellpadding="0" width="100%" id='providersFormElementsTable'></table>

JS :

JS:

createFormElement("Nickname","nickname")

function createFormElement(labelText, id) {

$("#providersFormElementsTable").html("<tr><td>Nickname</td><td><input type='text' id='"+id+"' name='nickname'></td><lable id='"+labelText+"'></lable></td></tr>");
$('#providersFormElementsTable').append('<br />');
}

This one does what you want dynamically, it just needs the id and labelText to make it work, which actually must be the only dynamic variables as only they will be changing. Your DOM structure will always remain the same .

这一个动态地做你想要的,它只需要 id 和 labelText 让它工作,这实际上必须是唯一的动态变量,因为只有它们会改变。您的 DOM 结构将始终保持不变。

WORKING DEMO:

工作演示:

Moreover, when you use the process you mentioned in your post you get only [object Object]. That is because when you call createProviderFormFields, it is a function call and hence it's returning an object for you. You will not be seeing the text box as it needs to be added . For that you need to strip individual content form the object, then construct the html from it.

此外,当您使用您在帖子中提到的过程时,您只会获得[object Object]. 那是因为当您调用 时createProviderFormFields,它是一个函数调用,因此它会为您返回一个对象。您不会看到文本框,因为它需要添加。为此,您需要从 中剥离单个内容object,然后从中构建 html。

It's much easier to construct just the html and change the ids of the label and input according to your needs.

仅构建 html 并id根据需要更改标签和输入的s要容易得多。

回答by GGSoft

FOR EXAMPLE YOU HAVE RECIEVED JASON DATA FROM SERVER.

例如,您已从服务器收到 JASON 数据。

                var obj = JSON.parse(msg);
                var tableString ="<table id='tbla'>";
                tableString +="<th><td>Name<td>City<td>Birthday</th>";


                for (var i=0; i<obj.length; i++){
                    //alert(obj[i].name);
                    tableString +=gg_stringformat("<tr><td>{0}<td>{1}<td>{2}</tr>",obj[i].name, obj[i].age, obj[i].birthday);
                }
                tableString +="</table>";
                alert(tableString);
                $('#divb').html(tableString);

HERE IS THE CODE FOR gg_stringformat

这是 gg_stringformat 的代码

function gg_stringformat() {
var argcount = arguments.length,
    string,
    i;

if (!argcount) {
    return "";
}
if (argcount === 1) {
    return arguments[0];
}
string = arguments[0];
for (i = 1; i < argcount; i++) {
    string = string.replace(new RegExp('\{' + (i - 1) + '}', 'gi'), arguments[i]);
}
return string;

}

}