使用jQuery将行添加到表的tbody

Anu*_*pam 68 jquery html-table rows dynamic

我正在尝试向表中添加行tbody.但我遇到了实现这个问题的问题.首先,从html页面更改下拉列表时调用发生所有事情的功能.我创建了一个tr包含所有td内部的字符串,其中包含html元素,文本和其他内容.但是当我尝试使用以下方法将生成的行添加到表中时:

$(newRowContent).appendTo("#tblEntAttributes tbody");
Run Code Online (Sandbox Code Playgroud)

我遇到了一个错误.表的名称是tblEntAttributes,我正在尝试将其添加到tbody.

实际上正在发生的事情是jQuery无法tblEntAttributes作为一个HTML元素.但是我可以使用它来访问它documemt.getElementById("tblEntAttributes");

有没有什么办法可以通过向tbody表中添加行来实现这一点.也许绕道或其他东西.

这是整个代码:

var newRowContent = "<tr><td><input type=\"checkbox\" id=\"" + chkboxId + "\" value=\"" + chkboxValue + "\"></td><td>" + displayName + "</td><td>" + logicalName + "</td><td>" + dataType + "</td><td><input type=\"checkbox\" id=\"chkAllPrimaryAttrs\" name=\"chkAllPrimaryAttrs\" value=\"chkAllPrimaryAttrs\"></td><td><input type=\"checkbox\" id=\"chkAllPrimaryAttrs\" name=\"chkAllPrimaryAttrs\" value=\"chkAllPrimaryAttrs\"></td></tr>";

$("#tblEntAttributes tbody").append(newRowContent); 
Run Code Online (Sandbox Code Playgroud)

我忘记提到的一件事是编写此代码的函数实际上是ajax调用的成功回调函数.我能够访问该表使用document.getElementById("tblEntAttributes")但由于某种原因$(#tblEntAttributes)似乎不起作用.

ᾠῗᵲ*_*ᵲᄐᶌ 91

("#tblEntAttributes tbody")

需要是

$("#tblEntAttributes tbody").

您没有选择具有正确语法的元素

这是两者的一个例子

$(newRowContent).appendTo($("#tblEntAttributes"));
Run Code Online (Sandbox Code Playgroud)

$("#tblEntAttributes tbody").append(newRowContent);
Run Code Online (Sandbox Code Playgroud)

工作 http://jsfiddle.net/xW4NZ/

  • 反转语法可能更具可读性:`$("#tblEntAttributes tbody").append(newRowContent);`. (5认同)

use*_*745 35

用这个

$("#tblEntAttributes tbody").append(newRowContent);
Run Code Online (Sandbox Code Playgroud)


Anu*_*pam 14

我从未遇到过这样一个奇怪的问题!OO

你知道问题是什么吗?$不起作用.我尝试了与jQuery相同的代码,jQuery("#tblEntAttributes tbody").append(newRowContent);它就像一个魅力!

不知道为什么会出现这个奇怪的问题

  • 您应该阅读有关jQuery.noConflict()的内容.可能是您正在使用其他库也使用$ alias http://api.jquery.com/jQuery.noConflict/ (9认同)

And*_*rew 5

这是使用您提到的 html 下拉列表的 appendTo 版本。它在“更改”上插入另一行。

$('#dropdown').on( 'change', function(e) {
    $('#table').append('<tr><td>COL1</td><td>COL2</td></tr>');
});
Run Code Online (Sandbox Code Playgroud)

举个例子让你玩玩。祝你好运!

http://jsfiddle.net/xtHaF/12/