简体   繁体   English

jQuery 将新行附加到表 - 检测现有行但不添加新行

[英]jQuery append new row to table - detecting existing rows but not adding new

I have a basic HTMl table like this...我有一个像这样的基本 HTMl 表...

 jQuery(document).ready(function() { /* Calculate Total */ jQuery('table tr.customRow').each(function(i, row) { console.log('Found Row'); jQuery(this).append('<tr>New Test Row</tr>'); }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <tr class="customRow"> <td> My Row 1 </td> </tr> <tr class="customRow"> <td> My Row 2 </td> </tr> <tr class="customRow"> <td> My Row 3 </td> </tr> </table>

I am trying to use jQuery to add a new <tr> above each found <tr> using append.我试图使用jQuery添加一个新<tr>每找到上面<tr>使用追加。 The console log shows that it is finding the rows but is not adding the new one.控制台日志显示它正在查找行但没有添加新行。

Where am I going wrong?我哪里错了?

You're not trying to add new tr s before existing tr s;您不是要在现有tr之前添加新的tr you're trying to insert them INTO them.你试图将它们插入到它们中。

Instead of:代替:

jQuery(this).append('<tr>New Test Row</tr>');

You want:你要:

jQuery(this).before('<tr>New Test Row</tr>');

Furthermore, as @Rory McCrossan points out, you can't have text nodes directly inside tr nodes - you need a td container.此外,正如@Rory McCrossan 指出的那样,您不能在tr节点内直接拥有文本节点 - 您需要一个td容器。

There's two issues in your code.您的代码中有两个问题。 Firstly the HTML you're trying to add is invalid.首先,您尝试添加的 HTML 无效。 <tr> elements cannot contain text nodes. <tr>元素不能包含文本节点。 You need to wrap the content in a td or th .您需要将内容包装在tdth

Secondly append() will be placing the new tr inside the existing tr , which again is invalid HTML.其次append()将把新的tr放在现有的tr ,这也是无效的 HTML。 Given your goal use before() instead.鉴于您的目标,请改用before()

Also note that, because the new content is the same in all cases, an each() loop is not required here.另请注意,由于新内容在所有情况下都相同,因此这里不需要each()循环。 jQuery will implicitly loop over the collection and create the content on every selected element for you. jQuery 将隐式循环遍历集合并为您在每个选定元素上创建内容。 Try this:尝试这个:

 jQuery(function($) { $('table tr.customRow').before('<tr><td>New Test Row</td></tr>'); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <tr class="customRow"> <td>My Row 1</td> </tr> <tr class="customRow"> <td>My Row 2</td> </tr> <tr class="customRow"> <td>My Row 3</td> </tr> </table>

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

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