我使用下面的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();
}
答案 0 :(得分:1)
我会建议这个
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>