简体   繁体   English

用jQuery创建表-追加

[英]Create table with jQuery - append

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/

This line: 这行:

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

Appends to the div#here_table not the new table . 追加到div#here_table而不是new 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. 希望这会有所帮助。

You need to append the tr inside the table so I updated your selector inside your loop and removed the closing table because 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 tr to the div here_table. 主要问题是您将tr附加到div here_table。

Edit: Here is a JavaScript version if performance is a concern. 编辑: 如果您担心性能,这是一个JavaScript版本。 Using document fragment will not cause a reflow for every iteration of the loop 使用文档片段不会在循环的每次迭代中导致重排

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);

When you use append , jQuery expects it to be well-formed HTML (plain text counts). 当您使用append ,jQuery期望它是格式正确的HTML(纯文本计数)。 append is not like doing += . 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);

Or do it this way to use ALL jQuery. 或者以这种方式使用所有jQuery。 The each can loop through any data be it DOM elements or an array/object. 每个对象都可以遍历任何数据,无论是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/

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. 这还允许您动态地向表中添加行和列,而无需对字段名进行硬编码。

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");               
    }           
}

Or static HTML without the loop for creating some links (or whatever). 或静态HTML,没有用于创建某些链接(或其他链接)的循环。 Place the <div id="menu"> on any page to reproduce the 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>

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! 最好的祝福!

A working example using the method mentioned above and using JSON to represent the data. 一个使用上述方法并使用JSON表示数据的工作示例。 This is used in my project of dealing with ajax calls fetching data from server. 这在我处理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' :'$5000' , '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' :'$5000' , 'd': 'Edit/Delete' },
         {'a': 'Real Estate',  'b' :'Property',  'c' :'$500000' , 'd': 'Edit/Delete' }
        ]};

    feed_table(t);
});

As for me, this approach is prettier: 对我来说,这种方法更漂亮:

String.prototype.embraceWith = function(tag) {
    return "<" + tag + ">" + this + "</" + tag + ">";
};

var results = [
  {type:"Fiat", model:500, color:"white"}, 
  {type:"Mercedes", model: "Benz", color:"black"},
  {type:"BMV", model: "X6", color:"black"}
];

var tableHeader = ("Type".embraceWith("th") + "Model".embraceWith("th") + "Color".embraceWith("th")).embraceWith("tr");
var tableBody = results.map(function(item) {
    return (item.type.embraceWith("td") + item.model.toString().embraceWith("td") + item.color.embraceWith("td")).embraceWith("tr")
}).join("");

var table = (tableHeader + tableBody).embraceWith("table");

$("#result-holder").append(table);

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: 示例结果:

示例结果


i prefer the most readable and extensible way using jquery. 我更喜欢使用jquery的最易读和可扩展的方式。
Also, you can build fully dynamic content on the fly. 此外,您可以动态构建完全动态的内容。
Since jquery version 1.4 you can pass attributes to elements which is, 从jquery 1.4版开始,您可以将属性传递给元素,即
imho, a killer feature. 恕我直言,杀手级功能。 Also the code can be kept cleaner. 此外,代码可以保持整洁。

$(function(){

        var tablerows = new Array();

        $.each(['result1', 'result2', 'result3'], function( index, value ) {
            tablerows.push('<tr><td>' + value + '</td></tr>');
        });

        var table =  $('<table/>', {
           html:  tablerows
       });

        var div = $('<div/>', {
            id: 'here_table',
            html: table
        });

        $('body').append(div);

    });

Addon: passing more than one "html" tag you've to use array notation like: eg 插件:传递多个“ html”标签,您必须使用数组表示法,例如:

var div = $('<div/>', {
            id: 'here_table',
            html: [ div1, div2, table ]
        });

best Rgds. 最佳Rgds。
Franz 弗朗兹

<table id="game_table" border="1">

and Jquery 和jQuery

var i;
for (i = 0; ii < 10; i++) 
{

        var tr = $("<tr></tr>")
        var ii;
        for (ii = 0; ii < 10; ii++) 
        {
        tr.append(`<th>Firstname</th>`)
        }

$('#game_table').append(tr)
}

this is most better 这是最好的

html html

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

jQuery jQuery的

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

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

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

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

It is important to note that you could use Emmet to achieve the same result. 重要的是要注意,您可以使用Emmet获得相同的结果。 First, check what Emmet can do for you at https://emmet.io/ 首先,在https://emmet.io/检查Emmet可以为您做什么

In a nutshell, with Emmet, you can expand a string into a complexe HTML markup as shown in the examples below: 简而言之,使用Emmet,您可以将字符串扩展为复杂的HTML标记,如下例所示:

Example #1 例子1

ul>li*5

... will produce ...将产生

<ul>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
</ul>

Example #2 范例#2

div#header+div.page+div#footer.class1.class2.class3

... will produce ...将产生

<div id="header"></div>
<div class="page"></div>
<div id="footer" class="class1 class2 class3"></div>

And list goes on. 清单还在继续。 There are more examples at https://docs.emmet.io/abbreviations/syntax/ https://docs.emmet.io/abbreviations/syntax/上有更多示例

And there is a library for doing that using jQuery. 并且有一个使用jQuery完成此操作的库。 It's called Emmet.js and available at https://github.com/christiansandor/Emmet.js 它称为Emmet.js,可从https://github.com/christiansandor/Emmet.js获得。

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

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