我使用jQuery向表中添加一行作为最后一行。

我是这样做的:

$('#myTable').append('<tr><td>my data</td><td>more data</td></tr>');

您可以向这样的表中添加的内容(例如输入、选择、行数)是否有限制?有不同的方法吗?


当前回答

试试这个:非常简单的方法

$('<tr><td>3</td></tr><tr><td>4</td></tr>').appendTo(“#myTable tbody”);<script src=“https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js“></script><table id=“myTable”><tbody><tr><td>1</td></tr><tr><td>2</td></tr></tbody></table>

其他回答

jQuery有一个内置的工具,可以随时操作DOM元素。

您可以像这样向表中添加任何内容:

$("#tableID").find('tbody')
    .append($('<tr>')
        .append($('<td>')
            .append($('<img>')
                .attr('src', 'img.png')
                .text('Image cell')
            )
        )
    );

jQuery中的$(“<some tag>”)是一个标记对象,它可以有几个可以设置和获取的attr属性,以及文本,它表示标记之间的文本:<tag>text</tag>。

这是一些非常奇怪的缩进,但您更容易看到这个示例中的情况。

在我看来,最快和明确的方法是

//Try to get tbody first with jquery children. works faster!
var tbody = $('#myTable').children('tbody');

//Then if no tbody just select your table 
var table = tbody.length ? tbody : $('#myTable');

//Add row
table.append('<tr><td>hello></td></tr>');

这是演示Fiddle

此外,我还可以推荐一个小函数来进行更多的html更改

//Compose template string
String.prototype.compose = (function (){
var re = /\{{(.+?)\}}/g;
return function (o){
        return this.replace(re, function (_, k){
            return typeof o[k] != 'undefined' ? o[k] : '';
        });
    }
}());

如果你用我的弦乐器,你可以这样做

var tbody = $('#myTable').children('tbody');
var table = tbody.length ? tbody : $('#myTable');
var row = '<tr>'+
    '<td>{{id}}</td>'+
    '<td>{{name}}</td>'+
    '<td>{{phone}}</td>'+
'</tr>';


//Add row
table.append(row.compose({
    'id': 3,
    'name': 'Lee',
    'phone': '123 456 789'
}));

这里是演示不停摆弄

这可以使用jQuery的“last()”函数轻松完成。

$("#tableId").last().append("<tr><td>New row</td></tr>");

这是一些hacketi黑客代码。我想在HTML页面中维护一个行模板。表行0…n是在请求时呈现的,这个示例有一个硬编码行和一个简化的模板行。模板表是隐藏的,行标记必须在有效表中,否则浏览器可能会将其从DOM树中删除。添加行使用计数器+1标识符,当前值保持在数据属性中。它保证每一行都有唯一的URL参数。

我已经在Internet Explorer 8、Internet Explorer 9、Firefox、Chrome、Opera、诺基亚Lumia 800、诺基亚C7(带Symbian 3)、Android股票和Firefox测试版浏览器上运行了测试。

<table id="properties">
<tbody>
  <tr>
    <th>Name</th>
    <th>Value</th>
    <th>&nbsp;</th>
  </tr>
  <tr>
    <td nowrap>key1</td>
    <td><input type="text" name="property_key1" value="value1" size="70"/></td>
    <td class="data_item_options">
       <a class="buttonicon" href="javascript:deleteRow()" title="Delete row" onClick="deleteRow(this); return false;"></a>
    </td>
  </tr>
</tbody>
</table>

<table id="properties_rowtemplate" style="display:none" data-counter="0">
<tr>
 <td><input type="text" name="newproperty_name_\${counter}" value="" size="35"/></td>
 <td><input type="text" name="newproperty_value_\${counter}" value="" size="70"/></td>
 <td><a class="buttonicon" href="javascript:deleteRow()" title="Delete row" onClick="deleteRow(this); return false;"></a></td>
</tr>
</table>
<a class="action" href="javascript:addRow()" onclick="addRow('properties'); return false" title="Add new row">Add row</a><br/>
<br/>

- - - - 
// add row to html table, read html from row template
function addRow(sTableId) {
    // find destination and template tables, find first <tr>
    // in template. Wrap inner html around <tr> tags.
    // Keep track of counter to give unique field names.
    var table  = $("#"+sTableId);
    var template = $("#"+sTableId+"_rowtemplate");
    var htmlCode = "<tr>"+template.find("tr:first").html()+"</tr>";
    var id = parseInt(template.data("counter"),10)+1;
    template.data("counter", id);
    htmlCode = htmlCode.replace(/\${counter}/g, id);
    table.find("tbody:last").append(htmlCode);
}

// delete <TR> row, childElem is any element inside row
function deleteRow(childElem) {
    var row = $(childElem).closest("tr"); // find <tr> parent
    row.remove();
}

PS:我把所有学分都给了jQuery团队;他们值得拥有一切。没有jQuery的JavaScript编程——我甚至不想去想那个噩梦。

上面的答案非常有用,但当学生参考此链接从表单中添加数据时,他们通常需要一个示例。

我想提供一个示例,从from获取输入,并使用.after()使用字符串插值将tr插入到表中。

function add(){
  let studentname = $("input[name='studentname']").val();
  let studentmark = $("input[name='studentmark']").val();

  $('#student tr:last').after(`<tr><td>${studentname}</td><td>${studentmark}</td></tr>`);
}

函数add(){let studentname=$(“input[name='studentname']”).val();let studentmark=$(“input[name='studentmark']”).val();$('#student-tr:last').after(`<tr><td>${studentname}</td><td>${studentmark}</td></tr>`);}<script src=“https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js“></script><!DOCTYPE html><html><head><style>表{字体系列:arial,sans-serif;边界塌陷:塌陷;宽度:100%;}td,第{边框:1px实心#dddddd;文本对齐:左侧;填充:8px;}tr:第n个孩子(偶数){背景色:#dddddd;}</style></head><body><表单><input-type='text'name='studentname'/><input-type='text'name='studentmark'/><input-type='button'onclick=“add()”value=“add new”/></form><table id=“学生”><thead><th>名称</th><th>标记</th></thead></table></body></html>