下面是我使用jquery显示动态控件的代码,其工作正常
<script type="text/javascript">
$(document).ready(function() {
$("input[value='Add']").click(function(e){
e.preventDefault();
var year = new Date().getFullYear(),
DDL_fromProfession = "<select name='ParametersFromSch' id='DDL_FromSchYear'>",
DDL_ToProfession = "<select name='ParametersToSch' id='DDL_ToSchYear'>";
for (var i = year; i >= 1950; --i) {
DDL_fromProfession += "<option text='" + i + "' value='" + i + "'>" + i + "</option>";
if (i != year) {
DDL_ToProfession += "<option text='" + i + "' value='" + i + "'>" + i + "</option>";
} else {
DDL_ToProfession += "<option text='Present' value='Present'>Present</option>";
}
}
DDL_fromProfession += "</select>";
DDL_ToProfession += "</select>";
var controls = "<tr><td>From "+ DDL_fromProfession + " To "+DDL_ToProfession+ "</td></tr>";
controls += "<br/><button type='button' class='btn_rmv'>Remove</button></td></tr>";
$('#Controls').append(controls);
return false;
});
$('#Controls').on('click', '.btn_rmv', function() {
var index = $(this).closest('tr').index() + 2
$('#Controls tr:nth-child(n+' + (index - 2) + ')').remove();
return false;
});
});
</script>
以下是我添加动态控件的视图页面代码:
<tr>
<td align="center">
<table id="Controls"> </table>
<form method="post" action="" class="button_to">
<div>
<input value="Add" type="submit" />
</div>
</form>
</td>
</tr>
但我使用删除按钮删除动态控件并且它无法正常工作,请建议我在哪里犯错误。谢谢
答案 0 :(得分:1)
只需删除添加两个下拉列表行末尾的</td></tr>
:
var controls = "<tr><td>From "+ DDL_fromProfession + " To "+DDL_ToProfession;
这阻止了将删除控件添加到表中。
仅在btn_rmv
s click()
函数中使用此行:
$(this).parent().parent().remove();
答案 1 :(得分:0)
您正在关闭行,然后添加删除按钮,因为删除按钮没有显示。
请在下面找到修改后的代码。
$(document).ready(function() {
$(document).ready(function() {
$("input[value='Add']").click(function(e)
{
e.preventDefault();
// var field = $("#field").val();
var year = new Date().getFullYear();
var DDL_fromProfession = "<select name='ParametersFromSch' id='DDL_FromSchYear'>";
for (var i = year; i >= 1950; --i) {
DDL_fromProfession += "<option text='" + i + "' value='" + i + "'>" + i + "</option>";
}
DDL_fromProfession += "</select>";
var DDL_ToProfession = "<select name='ParametersToSch' id='DDL_ToSchYear'>";
for (var j = year; j >= 1950; --j) {
if (j != year) {
DDL_ToProfession += "<option text='" + j + "' value='" + j + "'>" + j + "</option>";
}
else {
DDL_ToProfession += "<option text='Present' value='Present'>Present</option>";
}
}
DDL_ToProfession += "</select>";
var controls = "<tr><td>From "+ DDL_fromProfession + " To "+DDL_ToProfession+ "</td>";
controls += "<td><button type='button' class='btn_rmv'>Remove</button></td></tr>";
//$('#Controls').append(newRow);
$('#Controls').append(controls);
return false;
});
$('#Controls').on('click', '.btn_rmv', function() {
$(this).parent().parent().remove();
return false;
});
});
});
还删除了删除代码,因为之前的代码仅删除了所有字段而不是当前字段。