我使用 jQuery 通过以下脚本克隆表格主体:
//1. Add new row
$("#addNew").click(function(e) {
e.preventDefault();
var $tableBody = $("#dataTable");
var $trLast = $tableBody.find("tr:last");
var $trNew = $trLast.clone();
var suffix = $trNew.find(':input:first').attr('name').match(/\d+/);
$trNew.find("td:last").html('<a href="#" class="remove">Remove</a>');
$.each($trNew.find(':input'), function(i, val) {
// Replaced Name
var oldN = $(this).attr('name');
var newN = oldN.replace('[' + suffix + ']', '[' + (parseInt(suffix) + 1) + ']');
$(this).attr('name', newN);
//Replaced value
var type = $(this).attr('type');
if (type.toLowerCase() == "text") {
$(this).attr('value', '');
}
});
$trLast.after($trNew);
});
// 2. Remove
$('a.remove').live("click", function(e) {
e.preventDefault();
$(this).parent().parent().remove();
});
我正在尝试克隆以下内容:
<tr style="border:1px solid black">
<td>@Html.TextBoxFor(a => a[j].WarmUp)</td>
<td>@Html.TextBoxFor(a => a[j].ExerciseName)</td>
<td>@Html.TextBoxFor(a => a[j].CoolDown)</td>
<td>@Html.TextBoxFor(a => a[j].MomentOfTheDay)</td>
<td>@Html.TextBoxFor(a => a[j].ExerciseWeek)</td>
<td><select asp-items="Html.GetEnumSelectList<SampleMvcApp.Models.Days>()"></select></td>
<td>
@if (j > 0)
{
<a href="#" class="remove">Remove</a>
}
</td>
但是,当我只有所有 HTML.TextBox
时,它效果很好。或 <td>
内的任何其他文本标签,但是当我添加
<select asp-items="Html.GetEnumSelectList<SampleMvcApp.Models.Days>()"></select>`
它停止工作。
在
处获取错误var newN = oldN.replace('[' + suffix + ']', '[' + (parseInt(suffix) + 1) + ']');
有什么建议吗?
最佳答案
您的<select>
标签(包含在 jQuery 的 :input
选择器中)没有 name
属性,所以$(this).attr('name')
该标签将是未定义的。
因此oldN
也将是未定义的,因此会出现错误。
添加name
归因于您的<select>
标签,或搜索实际的 <input>
标签而不是 :input
将自己限制在文本框内:
$.each($trNew.find('input:text'), function (i, val) {
关于javascript - 无法读取 HTMLSelectElement 处未定义的属性 'replace',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44812492/