@model DynamicRowAdd.Models.Test
@{
ViewBag.Title = "Index";
}
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#myButton").click(function () {
alert('hi');
// Create elements dynamically
var newRow = "<tr><td>'@Html.TextBoxFor(x => x.Id, new { @Value = "1" })'</td><td>'@Html.TextBoxFor(x => x.Name, new { @Value = "Abcd" })'</td></tr>";
alert(newRow);
// Add the new dynamic row after the last row
$('#myTable tr:last').after(newRow);
});
});
</script>
<h2>Index</h2>
<table id="myTable">
<tr>
<td>
@Html.TextBoxFor(Model => Model.Id, new { @Value = "1" })
</td>
<td>
@Html.TextBoxFor(Model => Model.Name, new { @Value = "Abcd" })
</td>
</tr>
</table>
<button id="myButton">Add New Row</button>
上面的代码,当我尝试运行时,我得到hi作为警报。以下代码是单击按钮时未触发的情况。控件不在函数内部。为什么。?我做错了。
答案 0 :(得分:1)
$(document).ready(function(){
//Write your code here
});
<强> JS Fiddle 强>
答案 1 :(得分:1)
使用append方法无需指定任何tr ..如果你想在beggining中插入tr使用prepend()
$('#myTable').append(newRow);