javascript 使用 jQuery 向空表添加行时处理 tbody
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13999880/
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
Handling tbody when adding rows to an empty table with jQuery
提问by khalid13
I have an empty table in my code like so:
我的代码中有一个空表,如下所示:
<table id='rostertable'></table>
When I add a <tr>
using jQuery's append
function, then according to my chrome inspector, my table looks like this:
当我添加一个<tr>
using jQuery 的append
函数时,根据我的 chrome 检查器,我的表如下所示:
<table id='rostertable'><tbody><tr>...</tr></tbody></table>
It seems like the tbody got added by itself, and this causes problems later when I'm traversing the DOM.
似乎 tbody 是自己添加的,这会在稍后我遍历 DOM 时导致问题。
For consistency's sake, I figured it would be better if I added the tbody myself and appended directly to it. Is this possible? I tried making my placeholder <table id='rostertable'><tbody></tbody></table>
but the jQuery selector $('#rostertable tbody')
returns null and my chrome inspector doesn't show the tbody tags either.
为了保持一致性,我认为如果我自己添加 tbody 并直接附加到它会更好。这可能吗?我尝试制作占位符,<table id='rostertable'><tbody></tbody></table>
但 jQuery 选择器$('#rostertable tbody')
返回 null,我的 chrome 检查器也不显示 tbody 标签。
Edit:Never mind, it ended up being an unrelated bug in my javascript. At one point I was clearing out the contents of the table and running $("#rostertable").html(""), which of course deleted the tbody. I accepted the first valid answer to this question.
编辑:没关系,它最终成为我的 javascript 中一个无关的错误。有一次我正在清除表的内容并运行 $("#rostertable").html(""),这当然删除了 tbody。我接受了这个问题的第一个有效答案。
采纳答案by Adil
You should not
get null
, if no element matches the selector still you will get object
containing zero
elements.
你应该not
得到null
,如果没有元素匹配选择器,你仍然会得到object
包含zero
元素。
Your selector is returning tbody and you might be using some wrong method.
您的选择器正在返回 tbody,您可能使用了一些错误的方法。
alert($('#rostertable tbody').html());?
回答by Nope
To append to the tbdoy
your code should work as long as you append valid html.
附加到tbdoy
您的代码应该工作,只要您附加有效的 html。
The below works ok:
以下工作正常:
$('#rostertable tbody').append('<tr><td>new row - cell 1</td><td>new row - cell 2</td></tr>');
You need to make sure you append a <td>
as well as the <tr>
. For example in Chrome, the following will simple add an empty <tr>
您需要确保附加 a<td>
和<tr>
. 例如在 Chrome 中,下面将简单地添加一个空<tr>
$('#rostertable tbody').append('<tr>no cells added, just row</tr>');?