简体   繁体   English

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

[英]How do I create HTML table using jQuery dynamically?

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 tr and td elements taking id and labelText : 这个方法将创建labelText idlabelText trtd元素:

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 textInputBox using console.log , I get the following: 当我使用console.log打印textInputBox ,我得到以下内容:

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

What could be the issue? 可能是什么问题?

Thanks to @theghostofc who showed me path... :) 感谢@theghostofc向我展示了道路...... :)

You may use two options: 您可以使用两个选项:

  1. createElement 的createElement
  2. InnerHTML 的innerHTML

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. 恕我直言,你是混合对象和内部HTML。 Let's try with a pure inner html approach: 让我们尝试使用纯粹的内部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;
}

An example with a little less stringified 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);

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>

I understand you want to create stuff dynamically. 我知道你想动态创建东西。 That does not mean you have to actually construct DOM elements to do it. 这并不意味着您必须实际构建DOM元素才能执行此操作。 You can just make use of html to achieve what you want . 你可以使用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. 这个动态地做你想要的,它只需要id和labelText来使它工作,实际上它必须是唯一的动态变量,因为它们只会改变。 Your DOM structure will always remain the same . 您的DOM结构将始终保持不变。

WORKING DEMO: 工作演示:

Moreover, when you use the process you mentioned in your post you get only [object Object] . 此外,当您使用帖子中提到的过程时,您只能获得[object Object] That is because when you call createProviderFormFields , it is a function call and hence it's returning an object for you. 那是因为当你调用createProviderFormFields ,它是一个函数调用,因此它会为你返回一个对象。 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删除单个内容,然后从中构造html。

It's much easier to construct just the html and change the id s of the label and input according to your needs. 只需构造html并根据需要更改标签的id并输入就更容易了。

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;

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM