【问题标题】:How to add table rows to html table using JQuery如何使用 JQuery 将表行添加到 html 表
【发布时间】:2018-03-13 11:15:30
【问题描述】:

我是 JQuery 新手,我正在尝试将行追加到现有表中。

  1. 代码有什么问题?

  2. 如何在不指定列中的值的情况下插入空行?

  3. 有没有更好的方法来做到这一点?怎么样?

$(document).ready(function () {			 
			 var tbl = $('#mytable');
			 appendTableRow(tbl)
		});
		
		function appendTableRow(table) {			   
			var newrow = '';

			newrow += "<tr>";
			newrow += "<td>21</td>";
			newrow += "<td>22</td>";
			newrow += "</tr>";
			 			
			table.find('tbody tr:last').append(newrow);     
		}
table {
		border-collapse: collapse;
	}

	table td {
		border: 1px solid black;
	}  
  
  table th {
		border: 1px solid black;
	}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="mytable">
	  <thead>
		<th>Col1</th>
		<th>Col2</th>
	  </thead>
	  
	  <tbody>
		<tr>
		  <td>11</td>
		  <td>12</td>
		</tr>
	  </tbody>
	</table>

【问题讨论】:

标签: jquery html-table rows


【解决方案1】:

您的代码很好。只需附加到 tbody。

$(document).ready(function () {			 
			 var tbl = $('#mytable');
			 appendTableRow(tbl)
		});
		
		function appendTableRow(table) {			   
			var newrow = '';

			newrow += "<tr>";
			newrow += "<td>21</td>";
			newrow += "<td>22</td>";
			newrow += "</tr>";
			 			
			$('tbody').append(newrow);     
		}
table {
		border-collapse: collapse;
	}

	table td {
		border: 1px solid black;
	}  
  
  table th {
		border: 1px solid black;
	}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="mytable">
	  <thead>
		<th>Col1</th>
		<th>Col2</th>
	  </thead>
	  
	  <tbody>
		<tr>
		  <td>11</td>
		  <td>12</td>
		</tr>
	  </tbody>
	</table>

【讨论】:

    【解决方案2】:

    1)没有什么是错,它正在做它被写做的事情。以编程方式,它工作正常。

    (我差点觉得这是个刁钻的问题)

    2) 代替newrow += "&lt;td&gt;21&lt;/td&gt;"; 使用newrow += "&lt;td&gt; &lt;/td&gt;"; ?

    3) 有更好的方法吗?怎么样?

    ^ 这些类型的问题不在此处讨论。

    【讨论】:

    • 这不是一个技巧问题!如果您运行代码,您将看到没有创建新行。创建的两个单元格在第一行旁边连接。
    猜你喜欢
    • 2017-06-19
    • 1970-01-01
    • 2012-08-05
    • 2019-06-19
    • 2016-06-02
    • 1970-01-01
    • 2012-06-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多