Javascript 使用 jQuery 创建表 - 追加

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

Create table with jQuery - append

javascriptjqueryhtml

提问by Mark Fondy

I have on page div:

我在页面 div 上:

<div id="here_table"></div>

and in jquery:

在 jquery 中:

for(i=0;i<3;i++){
    $('#here_table').append( 'result' +  i );
}

this generating for me:

这为我生成:

<div id="here_table">
    result1 result2 result3 etc
</div>

I would like receive this in table:

我想在表中收到这个:

<div id="here_table">
    <table>
          <tr><td>result1</td></tr>
          <tr><td>result2</td></tr>
          <tr><td>result3</td></tr>
    </table>
</div>

I doing:

我在做:

$('#here_table').append(  '<table>' );

 for(i=0;i<3;i++){
    $('#here_table').append( '<tr><td>' + 'result' +  i + '</td></tr>' );
}

 $('#here_table').append(  '</table>' );

but this generate for me:

但这为我生成:

<div id="here_table">
    <table> </table> !!!!!!!!!!
          <tr><td>result1</td></tr>
          <tr><td>result2</td></tr>
          <tr><td>result3</td></tr>
</div>

Why? how can i make this correctly?

为什么?我怎样才能正确地做到这一点?

LIVE: http://jsfiddle.net/n7cyE/

现场直播:http: //jsfiddle.net/n7cyE/

回答by sransara

This line:

这一行:

$('#here_table').append( '<tr><td>' + 'result' +  i + '</td></tr>' );

Appends to the div#here_tablenot the new table.

附加到div#here_table不是新的table.

There are several approaches:

有几种方法:

/* Note that the whole content variable is just a string */
var content = "<table>"
for(i=0; i<3; i++){
    content += '<tr><td>' + 'result ' +  i + '</td></tr>';
}
content += "</table>"

$('#here_table').append(content);

But, with the above approach it is less manageable to add styles and do stuff dynamically with <table>.

但是,使用上述方法,添加样式和使用<table>.

But how about this one, it does what you expect nearly great:

但是这个怎么样,它做了你所期望的几乎很棒的事情:

var table = $('<table>').addClass('foo');
for(i=0; i<3; i++){
    var row = $('<tr>').addClass('bar').text('result ' + i);
    table.append(row);
}

$('#here_table').append(table);

Hope this would help.

希望这会有所帮助。

回答by Craig

You need to append the trinside the tableso I updated your selector inside your loop and removed the closing tablebecause it is not necessary.

你需要在tr里面追加,table所以我在你的循环中更新了你的选择器并删除了关闭,table因为它不是必需的。

$('#here_table').append(  '<table />' );

 for(i=0;i<3;i++){
    $('#here_table table').append( '<tr><td>' + 'result' +  i + '</td></tr>' );
}

The main problem was that you were appending the trto the divhere_table.

主要问题是您将 附加trdivhere_table。

Edit:Here is a JavaScript version if performance is a concern. Using document fragment will not cause a reflow for every iteration of the loop

编辑:如果性能是一个问题,这里有一个 JavaScript 版本。使用文档片段不会导致循环的每次迭代都发生回流

var doc = document;

var fragment = doc.createDocumentFragment();

for (i = 0; i < 3; i++) {
    var tr = doc.createElement("tr");

    var td = doc.createElement("td");
    td.innerHTML = "content";

    tr.appendChild(td);

    //does not trigger reflow
    fragment.appendChild(tr);
}

var table = doc.createElement("table");

table.appendChild(fragment);

doc.getElementById("here_table").appendChild(table);

回答by Rocket Hazmat

When you use append, jQuery expects it to be well-formed HTML (plain text counts). appendis not like doing +=.

当您使用 时append,jQuery 期望它是格式良好的 HTML(纯文本计数)。 append不是喜欢做+=

You need to make the table first, then append it.

您需要先制作表格,然后附加它。

var $table = $('<table/>');
for(var i=0; i<3; i++){
    $table.append( '<tr><td>' + 'result' +  i + '</td></tr>' );
}
$('#here_table').append($table);

回答by Thure Jason Fransen

Or do it this way to use ALL jQuery. The each can loop through any data be it DOM elements or an array/object.

或者以这种方式使用 ALL jQuery。each 可以遍历任何数据,无论是 DOM 元素还是数组/对象。

var data = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight'];
var numCols = 1;           


$.each(data, function(i) {
  if(!(i%numCols)) tRow = $('<tr>');

  tCell = $('<td>').html(data[i]);

  $('table').append(tRow.append(tCell));
});
?

http://jsfiddle.net/n7cyE/93/

http://jsfiddle.net/n7cyE/93/

回答by Aparna

To add multiple columns and rows, we can also do a string concatenation. Not the best way, but it sure works.

要添加多个列和行,我们还可以进行字符串连接。不是最好的方法,但它确实有效。

             var resultstring='<table>';
      for(var j=0;j<arr.length;j++){
              //array arr contains the field names in this case
          resultstring+= '<th>'+ arr[j] + '</th>';
      }
      $(resultset).each(function(i, result) {
          // resultset is in json format
          resultstring+='<tr>';
          for(var j=0;j<arr.length;j++){
              resultstring+='<td>'+ result[arr[j]]+ '</td>';
          }
          resultstring+='</tr>';
      });
      resultstring+='</table>';
          $('#resultdisplay').html(resultstring);

This also allows you to add rows and columns to the table dynamically, without hardcoding the fieldnames.

这还允许您动态地向表中添加行和列,而无需对字段名进行硬编码。

回答by Minko Gechev

Here is what you can do: http://jsfiddle.net/n7cyE/4/

这是你可以做的:http: //jsfiddle.net/n7cyE/4/

$('#here_table').append('<table></table>');
var table = $('#here_table').children();
 for(i=0;i<3;i++){
    table.append( '<tr><td>' + 'result' +  i + '</td></tr>' );
}

Best regards!

此致!

回答by lk.annamalai

Following is done for multiple file uploads using jquery:

以下是使用 jquery 对多个文件上传完成的:

File input button:

文件输入按钮:

<div>
 <input type="file" name="uploadFiles" id="uploadFiles" multiple="multiple" class="input-xlarge" onchange="getFileSizeandName(this);"/> 
</div>

Displaying File name and File size in a table:

在表格中显示文件名和文件大小:

<div id="uploadMultipleFilediv">
<table id="uploadTable" class="table table-striped table-bordered table-condensed"></table></div>

Javascript for getting the file name and file size:

用于获取文件名和文件大小的 Javascript:

function getFileSizeandName(input)
{
    var select = $('#uploadTable');
    //select.empty();
    var totalsizeOfUploadFiles = "";
    for(var i =0; i<input.files.length; i++)
    {
        var filesizeInBytes = input.files[i].size; // file size in bytes
        var filesizeInMB = (filesizeInBytes / (1024*1024)).toFixed(2); // convert the file size from bytes to mb
        var filename = input.files[i].name;
        select.append($('<tr><td>'+filename+'</td><td>'+filesizeInMB+'</td></tr>'));
        totalsizeOfUploadFiles = totalsizeOfUploadFiles+filesizeInMB;
        //alert("File name is : "+filename+" || size : "+filesizeInMB+" MB || size : "+filesizeInBytes+" Bytes");               
    }           
}

回答by HTMLJedi

Or static HTML without the loop for creating some links (or whatever). Place the <div id="menu">on any page to reproduce the HTML.

或者没有用于创建一些链接(或其他)的循环的静态 HTML。将<div id="menu">放在任何页面上以重现 HTML。

    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>HTML Masterpage</title>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>

        <script type="text/javascript">
            function nav() {
                var menuHTML= '<ul><li><a href="#">link 1</a></li></ul><ul><li><a href="#">link 2</a></li></ul>';
                $('#menu').append(menuHTML);
            }
        </script>

        <style type="text/css">
        </style>
    </head>
    <body onload="nav()">
        <div id="menu"></div>
    </body>
    </html>

回答by MSS

I wrote rather good function that can generate vertical and horizontal tables:

我写了相当不错的函数,可以生成垂直和水平表:

function generateTable(rowsData, titles, type, _class) {
    var $table = $("<table>").addClass(_class);
    var $tbody = $("<tbody>").appendTo($table);


    if (type == 2) {//vertical table
        if (rowsData.length !== titles.length) {
            console.error('rows and data rows count doesent match');
            return false;
        }
        titles.forEach(function (title, index) {
            var $tr = $("<tr>");
            $("<th>").html(title).appendTo($tr);
            var rows = rowsData[index];
            rows.forEach(function (html) {
                $("<td>").html(html).appendTo($tr);
            });
            $tr.appendTo($tbody);
        });

    } else if (type == 1) {//horsantal table 
        var valid = true;
        rowsData.forEach(function (row) {
            if (!row) {
                valid = false;
                return;
            }

            if (row.length !== titles.length) {
                valid = false;
                return;
            }
        });

        if (!valid) {
            console.error('rows and data rows count doesent match');
            return false;
        }

        var $tr = $("<tr>");
        titles.forEach(function (title, index) {
            $("<th>").html(title).appendTo($tr);
        });
        $tr.appendTo($tbody);

        rowsData.forEach(function (row, index) {
            var $tr = $("<tr>");
            row.forEach(function (html) {
                $("<td>").html(html).appendTo($tr);
            });
            $tr.appendTo($tbody);
        });
    }

    return $table;
}

usage example:

用法示例:

var title = [
    '????? ?????',
    '????? ?????????',
    '????? ?? ???'
];

var rows = [
    [number_format(data.source.area,2)],
    [number_format(data.intersection.area,2)],
    [number_format(data.deference.area,2)]
];

var $ft = generateTable(rows, title, 2,"table table-striped table-hover table-bordered");

$ft.appendTo( GroupAnalyse.$results );

var title = [
    '???',
    '?????? ????',
    '?????? ????',
    '?????',
    '????? ??? ?????',
];

var rows = data.edgesData.map(function (r) {
    return [
        r.directionText,
        r.lineLength,
        r.newLineLength,
        r.stateText,
        r.lineLengthDifference
    ];
});


var $et = generateTable(rows, title, 1,"table table-striped table-hover table-bordered");

$et.appendTo( GroupAnalyse.$results );

$('<hr/>').appendTo( GroupAnalyse.$results );

example result:

示例结果:

example result

示例结果

回答by Jacob CUI

A working example using the method mentioned above and using JSON to represent the data. This is used in my project of dealing with ajax calls fetching data from server.

使用上述方法并使用 JSON 表示数据的工作示例。这在我处理从服务器获取数据的 ajax 调用的项目中使用。

http://jsfiddle.net/vinocui/22mX6/1/

http://jsfiddle.net/vinocui/22mX6/1/

In your html: < table id='here_table' >< /table >

在你的 html 中:<table id='here_table'></table>

JS code:

JS代码:

function feed_table(tableobj){
    // data is a JSON object with
    //{'id': 'table id',
    // 'header':[{'a': 'Asset Tpe', 'b' : 'Description', 'c' : 'Assets Value', 'd':'Action'}], 
    // 'data': [{'a': 'Non Real Estate',  'b' :'Credit card',  'c' :'00' , 'd': 'Edit/Delete' },...   ]}

    $('#' + tableobj.id).html( '' );

    $.each([tableobj.header, tableobj.data], function(_index, _obj){
    $.each(_obj, function(index, row){
        var line = "";
        $.each(row, function(key, value){
            if(0 === _index){
                line += '<th>' + value + '</th>';    
            }else{
                line += '<td>' + value + '</td>';
            }
        });
        line = '<tr>' + line + '</tr>';
        $('#' + tableobj.id).append(line);
    });


    });    
}

// testing
$(function(){
    var t = {
    'id': 'here_table',
    'header':[{'a': 'Asset Tpe', 'b' : 'Description', 'c' : 'Assets Value', 'd':'Action'}], 
    'data': [{'a': 'Non Real Estate',  'b' :'Credit card',  'c' :'00' , 'd': 'Edit/Delete' },
         {'a': 'Real Estate',  'b' :'Property',  'c' :'0000' , 'd': 'Edit/Delete' }
        ]};

    feed_table(t);
});