我正在使用下面的 C# 来生成一个表。我需要一种添加按钮(在 html 表格末尾的自己的行上)的方法,按下该按钮将添加新的文本框行。
这是如何在 JQuery/JavaScript 中实现的?
protected void btnGreen_Click(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder(string.Empty);
sb.Append("<table>");
sb.Append("<tr>");
sb.Append("<th>Spl</th>");
foreach (System.Web.UI.WebControls.ListItem item in cbxTest.Items)
{
if (item.Selected) { sb.Append("<th>" + columnname + "</th>"); }
}
sb.Append("</tr>");
int z = 2;
sb.Append("<td><input type=\"text\" name=\"field1\"></td>");
foreach (System.Web.UI.WebControls.ListItem item in cbxTest.Items)
{
if(item.Selected) { sb.Append("<td><input type=\"text\" name=\"field " + z + "\"></td>"); }
z = z + 1;
}
sb.Append("</tr>");
sb.Append("</table>");
other.InnerHtml = sb.ToString();
}
最佳答案
我建议这样做
protected void btnGreen_Click(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder(string.Empty);
sb.Append("<table id=\"tab\">");
sb.Append("<thead>");
sb.Append("<tr>");
sb.Append("<th>Spl</th>");
foreach (System.Web.UI.WebControls.ListItem item in cbxTest.Items)
{
if (item.Selected) { sb.Append("<th>" + columnname + "</th>"); }
}
sb.Append("</tr>");
sb.Append("</thead>");
sb.Append("<tbody>");
sb.Append("<tr>");
int z = 2;
sb.Append("<td><input type=\"text\" name=\"field1\"></td>");
foreach (System.Web.UI.WebControls.ListItem item in cbxTest.Items)
{
if(item.Selected) { sb.Append("<td><input type=\"text\" name=\"field " + z + "\"></td>"); }
z = z + 1;
}
sb.Append("</tr>");
sb.Append("</tbody>");
sb.Append("<tfoot>");
sb.Append("<tr><td><button id=\"add\" type=\"button\">Add</button></td></tr>");
sb.Append("</tfoot>");
sb.Append("</table>");
other.InnerHtml = sb.ToString();
}
jQuery:
$(function() {
$("#add").on("click",function() {
var $row = $("#tab tbody tr").first().clone();
$row.find("input").val(""); // here you can also change names if needed
$("#tab tbody").append($row);
});
});
示例:
$(function() {
$("#add").on("click", function() {
var $row = $("#tab tbody tr").first().clone();
$row.find("input").val(""); // here you can also change names if needed
$("#tab tbody").append($row);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<table id="tab">
<thead>
<tr>
<th>Spl</th>
<th>columnname1</th>
<th>columnname2</th>
<th>columnname3</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" name="field1"></td>
<td><input type="text" name="field 2"></td>
<td><input type="text" name="field 3"></td>
<td><input type="text" name="field 4"></td>
</tr>
</tbody>
<tfoot>
<tr>
<td><button id="add" type="button">Add</button></td>
</tr>
</tfoot>
</table>
关于javascript - 使用 JQuery 在按钮单击时将行添加到表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48546429/