我有一个 HTML 表单,允许用户向表单中添加更多元素,但是在每行元素的旁边,有一个“删除”按钮,这个按钮链接到一个 jQuery 调用,但是新添加的元素单击按钮时不会删除,但是,最初硬编码到 HTML 中的元素将被删除。
这是我的代码:
$("[data-action]").each(function(i,a){
$(a).bind('click',function(){
switch ($(a).attr("data-action")) {
case "AddQualificationField":
qual_add_current++;
var qual_add_html = '<div id="AddQualification' + qual_add_current + '" class="controls inline" style="margin-top: 5px;">' +
'<label for="AddQualificationType[' + qual_add_current + ']">Type:</label> <input type="text" name="AddQualificationType[' + qual_add_current + ']" id="AddQualificationType[' + qual_add_current + ']" placeholder="e.g. \'A\' Level" class="input-small" maxlength="75" /> ' +
'<label for="AddQualificationSubject[' + qual_add_current + ']">Subject:</label> <input type="text" name="AddQualificationSubject[' + qual_add_current + ']" id="AddQualificationSubject[' + qual_add_current + ']" class="input-small" maxlength="75" /> ' +
'<label for="AddQualificationGrade[' + qual_add_current + ']">Grade:</label> <input type="text" name="AddQualificationGrade[' + qual_add_current + ']" id="AddQualificationGrade[' + qual_add_current + ']" class="input-small" maxlength="20" /> ' +
'<button type="button" class="btn" data-action="RemoveQual" data-qualid="' + qual_add_current + '"><i class="icon-remove"></i></button>' +
'</div>';
$("fieldset#AddQualifications").append(qual_add_html);
break;
case "RemoveQual":
var qual_id = parseInt($(a).attr("data-qualid"));
if (confirm("Are you sure that you want to do this?")) {
$("div#AddQualification" + qual_id).remove();
}
break;
}
});
});